- Notifications
You must be signed in to change notification settings - Fork72
Webpack loader for svelte components.
License
sveltejs/svelte-loader
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Undecided yet what bundler to use? We suggest usingSvelteKit, or Vite withvite-plugin-svelte.
npm install --save svelte svelte-loader
Configure inside yourwebpack.config.js
:
...resolve:{// see below for an explanationalias:{svelte:path.resolve('node_modules','svelte/src/runtime')// Svelte 3: path.resolve('node_modules', 'svelte')},extensions:['.mjs','.js','.svelte'],mainFields:['svelte','browser','...'],conditionNames:['svelte','browser','...'],},module:{rules:[ ...// The following two loader entries are only needed if you use Svelte 5+ with TypeScript.// Also make sure your tsconfig.json includes `"useDefineForClassFields": true` or "target" is at least "ES2022"` in order to not downlevel class syntax{test:/\.svelte\.ts$/,use:["svelte-loader",{loader:"ts-loader",options:{transpileOnly:true}}],},// This is the config for other .ts files - the regex makes sure to not process .svelte.ts files twice{test:/(?<!\.svelte)\.ts$/,loader:"ts-loader",options:{transpileOnly:true,// you should use svelte-check for type checking}},{// Svelte 5+:test:/\.(svelte|svelte\.js)$/,// Svelte 3 or 4:// test: /\.svelte$/,// In case you write Svelte in HTML (not recommended since Svelte 3):// test: /\.(html|svelte)$/,use:'svelte-loader'},{// required to prevent errors from Svelte on Webpack 5+, omit on Webpack 4test:/node_modules\/svelte\/.*\.mjs$/,resolve:{fullySpecified:false}}...]}...
Check out theexample project.
Theresolve.alias
option is used to make sure that only one copy of the Svelte runtime is bundled in the app, even if you arenpm link
ing in dependencies with their own copy of thesvelte
package. Having multiple copies of the internal scheduler in an app, besides being inefficient, can also cause various problems.
Webpack'sresolve.mainFields
option determines which fields inpackage.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).
Webpack'sresolve.conditionNames
option determines which fields in theexports
inpackage.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).
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 theemitCss
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. AddMiniCssExtractPlugin to the mix to output the css to a separate file.
constMiniCssExtractPlugin=require('mini-css-extract-plugin'); ...module:{rules:[ ...{test:/\.(svelte|svelte\.js)$/,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:[newMiniCssExtractPlugin('styles.css'), ...]...
Additionally, if you're using multiple entrypoints, you may wish to changenew MiniCssExtractPlugin('styles.css')
fornew MiniCssExtractPlugin('[name].css')
to generate one CSS file per entrypoint.
Warning: in production, if you have setsideEffects: false
in yourpackage.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}},},...
JavaScript source maps are enabled by default, you just have to use an appropriatewebpack devtool.
To enable CSS source maps, you'll need to useemitCss
and pass thesourceMap
option to thecss-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:[newMiniCssExtractPlugin('styles.css'), ...]...};
This should create an additionalstyles.css.map
file.
You can specify additional arbitrary compilation options with thecompilerOptions
config key, which are passed directly to the underlying Svelte compiler:
...use:{loader:'svelte-loader',options:{compilerOptions:{// additional compiler options heregenerate:'ssr',// for example, SSR can be enabled here}},},...
Installsvelte-preprocess and add it to the loader options:
constsveltePreprocess=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 alang
tag indicating the language that should be preprocessed. In the case of TypeScript, installtypescript
and addlang="ts"
to your script tags.
Hot Module Reloading is currently not supported for Svelte 5+
This loader supports component-level HMR via the community supportedsvelte-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 atsvelte-hmr (for now).
Configure inside yourwebpack.config.js
:
// It is recommended to adjust svelte options dynamically, by using// environment variablesconstmode=process.env.NODE_ENV||'development';constprod=mode==='production';module.exports={ ...module:{rules:[ ...{test:/\.(svelte|svelte\.js)$/,use:{loader:'svelte-loader',options:{compilerOptions:{// NOTE Svelte's dev mode MUST be enabled for HMR to workdev:!prod,// Default: false},// NOTE emitCss: true is currently not supported with HMR// Enable it for production to output separate css fileemitCss:prod,// Default: false// Enable HMR only for dev modehotReload:!prod,// Default: false// Extra HMR options, the defaults are completely fine// You can safely omit hotOptions altogetherhotOptions:{// Prevent preserving local component statepreserveLocalState:false,// If this string appears anywhere in your component's code, then local// state won't be preserved, even when noPreserveState is falsenoPreserveStateKey:'@!hmr',// Prevent doing a full reload on next HMR update after fatal errornoReload:false,// Try to recover after runtime errors in component initoptimistic: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:[newwebpack.HotModuleReplacementPlugin(), ...]}
You also need to add theHotModuleReplacementPlugin. There are multiple ways to achieve this.
If you're using webpack-dev-server, you can just pass it thehot
option to add the plugin automatically.
Otherwise, you can add it to your webpack config directly:
constwebpack=require('webpack');module.exports={ ...plugins:[newwebpack.HotModuleReplacementPlugin(), ...]}
It is advised to inline any css@import
in component's style tag before it hitscss-loader
.
This ensures equal css behavior when using HMR withemitCss: false
and production.
Installsvelte-preprocess
,postcss
,postcss-import
,postcss-load-config
.
Configuresvelte-preprocess
:
constsveltePreprocess=require('svelte-preprocess');...module.exports={ ...module:{rules:[ ...{test:/\.(svelte|svelte\.js)$/,use:{loader:'svelte-loader',options:{preprocess:sveltePreprocess({postcss:true})}}}...]},plugins:[newwebpack.HotModuleReplacementPlugin(), ...]}...
Createpostcss.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 withpostcss
throughsvelte-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 withpostcss
through webpack rules, and svelte component's css is being processed withpostcss
throughsvelte-preprocess
.
MIT
About
Webpack loader for svelte components.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.