css文件對于webpack來說和普通模塊沒有任何區別。通過style-loader和css-loader可以對css文件做解析,實現css模塊化。
內嵌的CSS【不推薦使用】
webpack默認是將css直接注入到html中,這種方法并不具有通用性,不推薦使用(百度首頁采用的就是講css注入到html,但我還是不推薦使用,除非是超級簡單的網頁或者對速度有極致要求的網頁)
webpack.config.js 代碼如下:
{
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}
獨立的CSS
結合使用extract-text-webpack-plugin
,可以生成一個獨立的css文件,結合代碼分離可以有兩種方式:
- 每個初始塊創建一個css文件,然后在別的依賴塊中引入樣式,可以優化初始化加載時間。
- 每個初始塊創建一個css文件,同時包含了依賴塊中的樣式,更適合多入口點的小型app,因為可以利用緩存來減少http請求。(通過設置
new ExtractTextPlugin("style.css", { allChunks: true })
開啟)
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
// The standard entry point and output config
entry: {
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")
]
}
將得到以下輸出文件:
- post.js/post.css
- about.js/about.css
- 1.js/2.js(包含內嵌樣式 或者 設置allChunks: true不包含內嵌樣式)
抽離公共CSS樣式
結合CommonsChunkPlugin
插件可以抽離公共CSS文件。
plugins: [
new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
new ExtractTextPlugin("[name].css")
]