样式嵌入
通过使用style-loader和css-loader,webpack可以将样式文件打包进一个js包中(javascript bundle),你可以对你的样式进行模块化,就像require(‘./stylesheets.css’);
安装
npm install style-loader css-loader --save-dev
配置
以下这个示例能使用require()css:
{
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}
使用
// in your modules just require the stylesheet
// This has the side effect that a <style>-tag is added to the DOM.
require("./stylesheet.css");
分离出css bundle
结合 extract-text-webpack-plugin,webpack在本地输出一个css文件。
运用code spliting 我们可以用两种模式来分离出css:
* 为每个初始块创建一个css文件,并将样式表嵌入其他chunks。
* 为每个初始块创建一个css文件,它还包含附加块的样式。
推荐使用第一种模式,因为它对于初始页面加载时间是最佳的。在具有多个入口点的小应用程序中,由于HTTP请求开销和缓存,第二种模式可能更好
插件安装
npm install extract-text-webpack-plugin --save
概括
要使用插件,你需要用一个特殊的loader去标记那些要移动至css文件中的模块。在webpack编译中的优化阶段后,插件会去检查哪些模块与提取相关(在一种模式中,只在一个init chunk中的),此外,模块在原始包中重新编译,并替换为空模块。
样式从初始块到单独的css输出文件
此示例显示多个入口点,但也适用于单个入口点。
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
// The standard entry point and output config entry: { posts: "./posts", post: "./post", about: "./about" },
output: {
filename: "[name].js", chunkFilename: "[id].js" },
module: {
loaders: [ // Extract css files { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
// Optionally extract less files
// or any other compile-to-css language
{
test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") }
// You could also use other loaders the same way. I. e. the autoprefixer-loader
]
},
// Use the plugin to specify the resulting filename (and add needed behavior to the compiler)
plugins: [ new ExtractTextPlugin("[name].css")
]
}
你将会的到如下输出文件:
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (含有嵌入的样式)
所有样式都在单独的css输出文件中
要使用第二种模式,您只需要将allChunks选项设置为true:
// ...
module.exports = {
// ...
plugins: [
new ExtractTextPlugin("style.css", {
allChunks: true
})
]
}
得到如下输出文件:
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (不含有嵌入的样式)
公用块中的样式
您可以使用单独的css文件与CommonsChunkPlugin结合使用。在这种情况下,也会发出公共块的css文件。
// ...
module.exports = {
// ...
plugins: [
new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
new ExtractTextPlugin("[name].css")
]
}
得到如下输出文件:
* commons.js commons.css
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (contain embedded styles)