webpack強大之處在於可以將CSS當做一個資源模塊進行管理和加載
基本使用:
安裝webpack的加載插件style-loader和css-loader:
npm install style-loader css-loader --save-dev
修改配置文件webpack.config.js:
var webpack = require('webpack');
module.exports = {
//context: __dirname + "/src", //指定了工作的目錄,相當如base路徑
entry: "./src/app.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devtool: "#source-map",
module: {
loaders: [
// Transpile any JavaScript file:
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
},
]
},
resolve: {
alias: { //將常用的lib在這里設置別名
//"bootstrap.css": "bootstrap/dist/css/bootstrap.css"
}
}
test: /\.css$/
這里設置了加載器
app.js中
require("./test.css");
最后執行webpack命令,test.css會被打包到bundle.js中。。。。NB
上面的方式會將CSS打包到JS文件中,雖然很NB但總歸是怪怪的
沒關系,還是有方案將css單獨拿出來的,這里用到另一個插件extract-text-webpack-plugin
還是先安裝
npm install extract-text-webpack-plugin --save
修改配置文件如下:
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
//context: __dirname + "/src", //指定了工作的目錄,相當如base路徑
entry: "./src/app.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devtool: "#source-map",
module: {
loaders: [
// Transpile any JavaScript file:
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
]
},
resolve: {
alias: { //將常用的lib在這里設置別名
//"bootstrap.css": "bootstrap/dist/css/bootstrap.css"
}
},
// Use the plugin to specify the resulting filename (and add needed behavior to the compiler)
plugins: [
new ExtractTextPlugin("[name].css")
]
}
執行命令,這時候dist里面會有多出來的.css文件了
將多個CSS文件打包到一個CSS文件
還是上面的配置文件,修改下面的地方:
plugins: [
new ExtractTextPlugin("style.css", {
allChunks: true
})
]
將公共部分隔離出去
new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
new ExtractTextPlugin("[name].css")