Skip to content

Commit 3d91717

Browse files
committed
Add emitCss documentation
1 parent 9bf59aa commit 3d91717

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

README.md

+85
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,91 @@ Configure inside your `webpack.config.js`:
2727

2828
Checkout [example setup](./example).
2929

30+
### Extracting CSS
31+
32+
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.
33+
34+
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 [ExtractTextPlugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) to the mix to output the css to a separate file.
35+
36+
```javascript
37+
...
38+
module: {
39+
rules: [
40+
...
41+
{
42+
test: /\.(html|svelte)$/,
43+
exclude: /node_modules/,
44+
use: {
45+
loader: 'svelte-loader',
46+
options: {
47+
emitCss: true,
48+
},
49+
},
50+
},
51+
{
52+
test: /\.css$/,
53+
use: ExtractTextPlugin.extract({
54+
fallback: 'style-loader',
55+
use: 'css-loader',
56+
}),
57+
},
58+
...
59+
]
60+
},
61+
...
62+
plugins: [
63+
new ExtractTextPlugin('styles.css'),
64+
...
65+
]
66+
...
67+
```
68+
69+
Alternatively, if you're handling styles in some other way and just want to prevent the CSS being added to your JavaScript bundle, use `css: false`.
70+
71+
### Source maps
72+
73+
JavaScript source maps are enabled by default, you just have to use an appropriate [webpack devtool](https://webpack.js.org/configuration/devtool/).
74+
75+
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:
76+
77+
```javascript
78+
module.exports = {
79+
...
80+
devtool: "source-map", // any "source-map"-like devtool is possible
81+
...
82+
module: {
83+
rules: [
84+
...
85+
{
86+
test: /\.(html|svelte)$/,
87+
exclude: /node_modules/,
88+
use: {
89+
loader: 'svelte-loader',
90+
options: {
91+
emitCss: true,
92+
},
93+
},
94+
},
95+
{
96+
test: /\.css$/,
97+
use: ExtractTextPlugin.extract({
98+
fallback: 'style-loader',
99+
use: [{ loader: 'css-loader', options: { sourceMap: true } }],
100+
}),
101+
},
102+
...
103+
]
104+
},
105+
...
106+
plugins: [
107+
new ExtractTextPlugin('styles.css'),
108+
...
109+
]
110+
...
111+
};
112+
```
113+
114+
This should create an additional `styles.css.map` file.
30115

31116
## License
32117

0 commit comments

Comments
 (0)