-
Notifications
You must be signed in to change notification settings - Fork 0
stylesheets
Through using the style-loader and the css-loader it's possible to embed stylesheets into a webpack javascript bundle. This way you can modularize your stylesheets with your other modules. This way stylesheets are as easy as require("./stylesheet.css").
Here is a configuration example that enables require() css:
{
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}For compile-to-css languages see the according loaders for configuration examples. You can pipe them...
Keep in mind that it's difficult to manage the execution order of modules, so design your stylesheets so that order doesn't matter. (But you can rely on the order in one css file.)
// in your modules just require the stylesheet
// This has the side effect that a <style>-tag is added to the DOM.
require("./stylesheet.css");In combination with the extract-text-webpack-plugin it's possible to generate a native css file.
With Code Splitting we can use two different modes:
- Create one css file per initial chunk (see Code Spitting) and embed stylesheets into additional chunks. (recommended)
- Create one css file for the complete bundle.
The first mode is recommended because it's optimial in regards to initial page loading time. In small apps with multiple entry points the second mode could be better because of HTTP request overheads and caching.
To use the plugin you need to flag modules that should be moved into the css file with a special loader. After the compilation in the optimizing phase of webpack the plugin checks which modules are relevant for extraction (in the first mode only these that are in an initial chunk). These modules are compiled for node.js usage and executed to get the content. Additionally the modules are recompiled in the original bundle and replaced with an empty module.
A new asset is created for the extracted modules.
This examples shows multiple entry points, but also works with a single entry point.
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports {
entry: {
posts: "./posts",
post: "./post",
about: "./about"
},
output: {
filename: "[name].js",
chunkFilename: "[id].js"
}
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.use("style-loader", "css-loader")
},
{
test: /\.less$/,
loader: ExtractTextPlugin.use("style-loader", "css-loader!less-loader")
}
]
},
plugins: [
new ExtractTextPlugin("[name].css")
]
}You'll get these output files:
-
posts.jsposts.css -
post.jspost.css -
about.jsabout.css -
1.js2.js(contain embedded styles)
To use the second mode you just need to set the option allChunks to true:
// ...
module.exports = {
// ...
plugins: [
new ExtractTextPlugin("style.css", {
allChunks: true
})
]
}You'll get these output files:
posts.jspost.jsabout.js-
1.js2.js(don't contain embedded styles) style.css