- 安装
postcss、postcss-loader、postcss-preset-env、cross-env、mini-css-extract-plugin
npm i postcss postcss-loader postcss-preset-env cross-env mini-css-extract-plugin -D
cross-env
: 用来设置环境变量mini-css-extract-plugin
:将打包后的文件中的css,分离出来
- 安装
css-loader、sass-loader style-loader
npm i style-loader css-loader sass-loader -D
- 在根目录下新建
postcss.config.js
配置文件
module.exports = {
plugins: [
require('postcss-preset-env')
]
}
- 在
webpack-prod-config.js
中配置
const isDevMode = process.env.NODE_ENV !== 'production'
const webpackConfigBase = {
mode: 'production',
module: {
rules: [
{
test: /\.((c|sa|sc)ss)$/i,
use: [
/* 1、执行顺序:从下到上(从右到左)
2、loader作用:
- css-loader: 将css文件编译成commonjs模块加载js中,里面内容是样式字符串
- style-loader:将js中的css,通过创建style标签添加html文件中
*/
{
loader: isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
},
'postcss-loader',
'sass-loader'
],
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: isDevMode ? 'static/css/style.css' : 'static/css/style.[contenthash].css',
chunkFilename: isDevMode ? 'static/css/style.[id].css' : 'static/css/style.[contenthash].[id].css'
}),
]
}
- 在
package.json
中配置
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack-prod-config.js"
},
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production": [
">0.2%",
"not dead",
"not op_mini all"
]
},
}
- 执行命令:
npm run build