安装postcss-loader 和postcss-preset-env
npm i postcss-loader postcss-preset-env -D
配置postcss-loader
module: {
rules: [
... // 其他配置
{
test: /\.((c|le)ss)$/,
use: [
// 'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
// postcss插件
[
'postcss-preset-env',
{
// 其他选项
}
]
]
}
}
},
'less-loader'
]
}]
... // 其他配置
}
在package.json设置browserslist
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production": [
"last 1 version",
">0.2%",
"not dead",
"not op_mini all"
]
}
完整的webpack.config.json 配置如下:
const { resolve } = require('path')
// webpack构建后生成html文件,同时把构建好入口js文件引入到生成的html文件中
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 如果要加载多文件css,不能使用 `extract-text-webpack-plugin` 而是用 mini-css-extract-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// process.env.NODE_ENV = 'development'
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/bundle.js',
path: resolve(__dirname, 'dist'),
clean: true
},
module: {
rules: [{
test: /\.((c|le)ss)$/,
use: [
// 'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
// postcss插件
[
'postcss-preset-env',
{
// 其他选项
}
]
]
}
}
},
'less-loader'
]
}, {
test: /\.(png|jpe?g|gig|svg|webp|JPG)$/,
type: 'asset',
generator: {
filename: 'imgs/[hash:8][ext][query]'
},
parser: {
dataUrlCondition: {
// 小于 8KB的图片会被Base64 处理
maxSize: 8*1024
}
}
}, {
// 其他资源
test: /\.(ttf|waff2?|mp4)/,
type: 'asset/resource',
generator: {
filename: 'media/[hash:8][ext][qeury]'
}
}, {
test: /\.html$/,
loader: 'html-loader'
}]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
})
],
mode: 'development',
devServer: {
compress: true,
port: 3000,
open: true,
watchFiles: ['./src/index.html']
}
}