• Stars
    star
    591
  • Rank 72,773 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Webpack loader for svelte components.

Undecided yet what bundler to use? We suggest using SvelteKit, or Vite with vite-plugin-svelte.

svelte-loader

Build Status

A webpack loader for svelte.

Install

npm install --save svelte svelte-loader

Usage

Configure inside your webpack.config.js:

  ...
  resolve: {
    // see below for an explanation
    alias: {
      svelte: path.resolve('node_modules', 'svelte/src/runtime') // Svelte 3: path.resolve('node_modules', 'svelte')
    },
    extensions: ['.mjs', '.js', '.svelte'],
    mainFields: ['svelte', 'browser', 'module', 'main'],
    conditionNames: ['svelte', 'browser', 'import']
  },
  module: {
    rules: [
      ...
      {
        test: /\.(html|svelte)$/,
        use: 'svelte-loader'
      },
      {
        // required to prevent errors from Svelte on Webpack 5+, omit on Webpack 4
        test: /node_modules\/svelte\/.*\.mjs$/,
        resolve: {
          fullySpecified: false
        }
      }
      ...
    ]
  }
  ...

Check out the example project.

resolve.alias

The resolve.alias option is used to make sure that only one copy of the Svelte runtime is bundled in the app, even if you are npm linking in dependencies with their own copy of the svelte package. Having multiple copies of the internal scheduler in an app, besides being inefficient, can also cause various problems.

resolve.mainFields

Webpack's resolve.mainFields option determines which fields in package.json are used to resolve identifiers. If you're using Svelte components installed from npm, you should specify this option so that your app can use the original component source code, rather than consuming the already-compiled version (which is less efficient).

resolve.conditionNames

Webpack's resolve.conditionNames option determines which fields in the exports in package.json are used to resolve identifiers. If you're using Svelte components installed from npm, you should specify this option so that your app can use the original component source code, rather than consuming the already-compiled version (which is less efficient).

Extracting CSS

If your Svelte components contain <style> tags, by default the compiler will add JavaScript that injects those styles into the page when the component is rendered. That's not ideal, because it adds weight to your JavaScript, prevents styles from being fetched in parallel with your code, and can even cause CSP violations.

A better option is to extract the CSS into a separate file. Using the emitCss option as shown below would cause a virtual CSS file to be emitted for each Svelte component. The resulting file is then imported by the component, thus following the standard Webpack compilation flow. Add MiniCssExtractPlugin to the mix to output the css to a separate file.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  ...
  module: {
    rules: [
      ...
      {
        test: /\.(html|svelte)$/,
        use: {
          loader: 'svelte-loader',
          options: {
            emitCss: true,
          },
        },
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              url: false, // necessary if you use url('/path/to/some/asset.png|jpg|gif')
            }
          }
        ]
      },
      ...
    ]
  },
  ...
  plugins: [
    new MiniCssExtractPlugin('styles.css'),
    ...
  ]
  ...

Additionally, if you're using multiple entrypoints, you may wish to change new MiniCssExtractPlugin('styles.css') for new MiniCssExtractPlugin('[name].css') to generate one CSS file per entrypoint.

Warning: in production, if you have set sideEffects: false in your package.json, MiniCssExtractPlugin has a tendency to drop CSS, regardless of whether it's included in your svelte components.

Alternatively, if you're handling styles in some other way and just want to prevent the CSS being added to your JavaScript bundle, use

...
use: {
  loader: 'svelte-loader',
  options: {
    compilerOptions: {
      css: false
    }
  },
},
...

Source maps

JavaScript source maps are enabled by default, you just have to use an appropriate webpack devtool.

To enable CSS source maps, you'll need to use emitCss and pass the sourceMap option to the css-loader. The above config should look like this:

module.exports = {
    ...
    devtool: "source-map", // any "source-map"-like devtool is possible
    ...
    module: {
      rules: [
        ...
        {
          test: /\.css$/,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                sourceMap: true
              }
            }
          ]
        },
        ...
      ]
    },
    ...
    plugins: [
      new MiniCssExtractPlugin('styles.css'),
      ...
    ]
    ...
};

This should create an additional styles.css.map file.

Svelte Compiler options

You can specify additional arbitrary compilation options with the compilerOptions config key, which are passed directly to the underlying Svelte compiler:

...
use: {
  loader: 'svelte-loader',
  options: {
    compilerOptions: {
      // additional compiler options here
      generate: 'ssr', // for example, SSR can be enabled here
    }
  },
},
...

Using preprocessors like TypeScript

Install svelte-preprocess and add it to the loader options:

const sveltePreprocess = require('svelte-preprocess');
...
use: {
  loader: 'svelte-loader',
  options: {
    preprocess: sveltePreprocess()
  },
},
...

Now you can use other languages inside the script and style tags. Make sure to install the respective transpilers and add a lang tag indicating the language that should be preprocessed. In the case of TypeScript, install typescript and add lang="ts" to your script tags.

Hot Reload

This loader supports component-level HMR via the community supported svelte-hmr package. This package serves as a testbed and early access for Svelte HMR, while we figure out how to best include HMR support in the compiler itself (which is tricky to do without unfairly favoring any particular dev tooling). Feedback, suggestion, or help to move HMR forward is welcomed at svelte-hmr (for now).

Configure inside your webpack.config.js:

// It is recommended to adjust svelte options dynamically, by using
// environment variables
const mode = process.env.NODE_ENV || 'development';
const prod = mode === 'production';

module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.(html|svelte)$/,
        use: {
          loader: 'svelte-loader',
          options: {
            compilerOptions: {
              // NOTE Svelte's dev mode MUST be enabled for HMR to work
              dev: !prod, // Default: false
            },

            // NOTE emitCss: true is currently not supported with HMR
            // Enable it for production to output separate css file
            emitCss: prod, // Default: false
            // Enable HMR only for dev mode
            hotReload: !prod, // Default: false
            // Extra HMR options, the defaults are completely fine
            // You can safely omit hotOptions altogether
            hotOptions: {
              // Prevent preserving local component state
              preserveLocalState: false,

              // If this string appears anywhere in your component's code, then local
              // state won't be preserved, even when noPreserveState is false
              noPreserveStateKey: '@!hmr',

              // Prevent doing a full reload on next HMR update after fatal error
              noReload: false,

              // Try to recover after runtime errors in component init
              optimistic: false,

              // --- Advanced ---

              // Prevent adding an HMR accept handler to components with
              // accessors option to true, or to components with named exports
              // (from <script context="module">). This have the effect of
              // recreating the consumer of those components, instead of the
              // component themselves, on HMR updates. This might be needed to
              // reflect changes to accessors / named exports in the parents,
              // depending on how you use them.
              acceptAccessors: true,
              acceptNamedExports: true,
            }
          }
        }
      }
      ...
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    ...
  ]
}

You also need to add the HotModuleReplacementPlugin. There are multiple ways to achieve this.

If you're using webpack-dev-server, you can just pass it the hot option to add the plugin automatically.

Otherwise, you can add it to your webpack config directly:

const webpack = require('webpack');

module.exports = {
  ...
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    ...
  ]
}

CSS @import in components

It is advised to inline any css @import in component's style tag before it hits css-loader.

This ensures equal css behavior when using HMR with emitCss: false and production.

Install svelte-preprocess, postcss, postcss-import, postcss-load-config.

Configure svelte-preprocess:

const sveltePreprocess = require('svelte-preprocess');
...
module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.(html|svelte)$/,
        use: {
          loader: 'svelte-loader',
          options: {
            preprocess: sveltePreprocess({
              postcss: true
            })
          }
        }
      }
      ...
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    ...
  ]
}
...

Create postcss.config.js:

module.exports = {
  plugins: [
    require('postcss-import')
  ]
}

If you are using autoprefixer for .css, then it is better to exclude emitted css, because it was already processed with postcss through svelte-preprocess before emitting.

  ...
  module: {
    rules: [
      ...
      {
        test: /\.css$/,
        exclude: /svelte\.\d+\.css/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader'
        ]
      },
      {
        test: /\.css$/,
        include: /svelte\.\d+\.css/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader'
        ]
      },
      ...
    ]
  },
  ...

This ensures that global css is being processed with postcss through webpack rules, and svelte component's css is being processed with postcss through svelte-preprocess.

License

MIT

More Repositories

1

svelte

Cybernetically enhanced web apps
JavaScript
75,642
star
2

kit

web development, streamlined
JavaScript
17,332
star
3

sapper

The next small thing in web development, powered by Svelte
TypeScript
7,031
star
4

realworld

SvelteKit implementation of the RealWorld app
Svelte
2,129
star
5

template

Template for building basic applications with Svelte
JavaScript
1,732
star
6

svelte-preprocess

A ✨ magical ✨ Svelte preprocessor with sensible defaults and support for: PostCSS, SCSS, Less, Stylus, Coffeescript, TypeScript, Pug and much more.
TypeScript
1,687
star
7

svelte-devtools

A browser extension to inspect Svelte application by extending your browser devtools capabilities
Svelte
1,312
star
8

language-tools

The Svelte Language Server, and official extensions which use it
TypeScript
1,128
star
9

vite-plugin-svelte

Svelte plugin for http://vitejs.dev/
JavaScript
787
star
10

sapper-template

Starter template for Sapper apps
JavaScript
706
star
11

prettier-plugin-svelte

Format your svelte components using prettier.
TypeScript
684
star
12

svelte-virtual-list

A virtual list component for Svelte apps
JavaScript
656
star
13

integrations

Ways to incorporate Svelte into your stack
633
star
14

gl

A (very experimental) project to bring WebGL to Svelte
JavaScript
608
star
15

community-legacy

Svelte community meetups, packages, resources, recipes, showcase websites, and more
Svelte
565
star
16

component-template

A base for building shareable Svelte components
JavaScript
551
star
17

rollup-plugin-svelte

Compile Svelte components with Rollup
JavaScript
489
star
18

learn.svelte.dev

A soup-to-nuts interactive tutorial on how to build apps with Svelte
Svelte
440
star
19

eslint-plugin-svelte3

An ESLint plugin for Svelte v3 components.
JavaScript
377
star
20

svelte-scroller

A <Scroller> component for Svelte apps
Svelte
337
star
21

template-webpack

Template for building basic Svelte applications with webpack
JavaScript
301
star
22

sites

Monorepo for the sites in the Svelte ecosystem
Svelte
277
star
23

svelte-repl

The <Repl> component used on the Svelte website
Svelte
273
star
24

rfcs

RFCs for changes to Svelte
269
star
25

eslint-plugin-svelte

ESLint plugin for Svelte using AST
TypeScript
242
star
26

sapper-studio

An electron app for building Sapper projects
HTML
220
star
27

v2.svelte.dev

The Svelte v2 website
HTML
209
star
28

svelte-hmr

HMR commons for Svelte 3
JavaScript
201
star
29

site-kit

Svelte
173
star
30

hn.svelte.dev

Hacker News clone built with Svelte and Sapper
Svelte
163
star
31

svelte-todomvc

TodoMVC implemented in Svelte
Svelte
137
star
32

svelte-subdivide

A component for building Blender-style layouts in Svelte apps
JavaScript
129
star
33

svelte-cli

Command line interface for Svelte
JavaScript
104
star
34

gestures

Svelte actions for cross-platform gesture detection
TypeScript
88
star
35

svelte-hackernews

WIP Hacker News clone written in Svelte
JavaScript
78
star
36

svelte-eslint-parser

Svelte parser for ESLint
TypeScript
74
star
37

svelte-custom-elements

Turn Svelte components into web components
JavaScript
49
star
38

svelte-extras

Extra methods for Svelte components
JavaScript
43
star
39

sapper-template-rollup

Starter Rollup template for Sapper apps
JavaScript
40
star
40

svelte-upgrade

Upgrade your Svelte templates for version 2
JavaScript
36
star
41

branding

Logos etc for Svelte and related projects
35
star
42

hn.svelte.technology

Hacker News, built with Sapper
HTML
35
star
43

svelte-transitions

Officially supported transition plugins for Svelte
JavaScript
34
star
44

examples

A collection of Svelte(Kit) examples
33
star
45

sapper-template-webpack

Starter webpack template for Sapper apps
JavaScript
33
star
46

kit-template-default

The default SvelteKit template, generated with create-svelte
Svelte
32
star
47

discord-bot

TypeScript
32
star
48

svelte-atom

Syntax, diagnostics, and other smarts for Svelte in Atom
JavaScript
30
star
49

community

27
star
50

svelte-dbmonster

Svelte implementation of DBMonster
JavaScript
26
star
51

template-custom-element

Template for building basic applications with Svelte and custom elements
HTML
21
star
52

generate-ssr

Server-side rendering for Svelte
JavaScript
20
star
53

kit-sandbox

A sandbox for maintainers
JavaScript
17
star
54

template-store

Demonstrating the use of svelte/store
JavaScript
17
star
55

svelte-transitions-draw

Draw transition plugin for Svelte
JavaScript
16
star
56

api.svelte.dev

The API worker source for https://api.svelte.dev
TypeScript
14
star
57

sapper-legacy.svelte.dev

Old docs site for Sapper
HTML
13
star
58

action-deploy-docs

github action for the svelte org to deploy documentation to the svelte api
TypeScript
12
star
59

svelte-bench

Benchmarks for Svelte
JavaScript
10
star
60

sveltegram

Sapper/Svelte remix of nextgram
JavaScript
8
star
61

svelte-transitions-fade

Fade transition plugin for Svelte
JavaScript
8
star
62

assets

Large static files used on the Svelte website
7
star
63

svelte-transitions-slide

Slide transition plugin for Svelte
JavaScript
5
star
64

svelte-transitions-fly

Fly transition plugin for Svelte
JavaScript
4
star
65

redirects

Redirect old Svelte websites to their shiny new equivalents
JavaScript
3
star