Home > Enterprise >  How to setup the pug pre-precessor for Svelte and Webpack?
How to setup the pug pre-precessor for Svelte and Webpack?

Time:11-24

In the Vue case below Webpack setup provides the Pug support:

{
  module: {
    rules: [
      // ...
      {
        test: /\.pug$/u,
        oneOf: [

          // For the single file components
          {
            resourceQuery: /^\?vue/u,
            use: [ "pug-plain-loader" ]
          },

          // For the retrieving of the <template> part from the external file
          {
            use: [
              {
                loader: "html-loader",
                options: {
                  minimize: { caseSensitive: true }
                }
              },
              "pug-html-loader"
            ]
          }
        ]
      }
    ]
  },
}

Will above setup work for the Svelte? I suppose no, and it's also requires some additional package providing mixins like if(), each(), etc.

Error example:

ERROR in ./OverflowSafeSingleLineLabel.svelte
Module build failed (from ../node_modules/svelte-loader/index.js):
Error: ParseError: Unexpected token (12:29)
10: <script lang="ts">
11: 
12:   export const rootElementTag: string = "div";
                                 ^
13: 
14: </script>

Please don't recommend me other project building tools like Rollup because current topic is focusing on the Webpack adaptation.

CodePudding user response:

First install svelte-preprocess: npm install --save-dev svelte-preprocess. Then adjust the webpack config and tell the Svelte loader to preprocess Svelte files:

import preprocess from 'svelte-preprocess'; // <-- this line is added
//...
   test: /\.svelte$/,
   loader: 'svelte-loader',
   options: { preprocess: preprocess() } // <-- this line is added

Now in your Svelte files you need to use lang=".." just like with Vue files to signal to svelte-preprocess that it needs to preprocess the contents before handing it off to the Svelte compiler.

<script lang="ts">
   const a: string = 'I can use TS in here';
</script>

<template lang="pug">
  I can use pug in here
</template>

The pug syntax is a little different and explained here: https://github.com/sveltejs/svelte-preprocess/blob/HEAD/docs/preprocessing.md#pug

  • Related