我们在使用webpack打包的时候,css被打包到js的文当中,有时候,我们想把css单独打包出来,不想和js放在同一个文件里面。
下面我们来看看该怎么做(webpack.config.js配置)
1 需要配置 css loader 注意:坑(使用用 MiniCssExtractPlugin.loader 替换style-loader)
rules:[
{ //处理css样式
test:/\.css$/,
use:[
//创建style表情,将样式放入
// 这个loader取代 'style-loader' 。作用:提取js中的css文件,
MiniCssExtractPlugin.loader,
//将css文件整理到js文件中
'css-loader'
]
}
]
2 需要下的插件为 mini-css-extract-plugin
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new MiniCssExtractPlugin()
],
webpack.config.js文件代码
const {resolve}=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const MiniCssExtractPlugin=require('mini-css-extract-plugin');
module.exports={
entry:'./src/js/index.js',
output:{
filename:'js/built.js', //输出路径 在js文件下
path:resolve(__dirname,'build')//__dername node.js变量,代表当前文件目录的绝对路径
},
module:{ //loader
rules:[
{ //处理css样式
test:/\.css$/,
use:[
//创建style表情,将样式放入
// 'style-loader'
// 这个loader取代 'style-loader' 。作用:提取js中的css文件,
MiniCssExtractPlugin.loader,
//将css文件整理到js文件中
'css-loader'
]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new MiniCssExtractPlugin()
],
mode:'development'
}
插件下载完成需要在webpack.json文件里面检查
{
"name": "webpack_test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"css-loader": "^3.5.3",
"file-loader": "^6.0.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.3.0",
"less": "^3.11.1",
"less-loader": "^6.1.0",
"style-loader": "^1.2.1",
"url-loader": "^4.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
//下载的插件
"dependencies": {
"mini-css-extract-plugin": "^0.9.0"
}
}
网友评论