webpack css兼容性处理踩坑记录
程序员文章站
2024-03-25 11:20:10
...
1、目录文件
2、全局配置需要的loader 和 plugins(已经安装webpack的前提下,全局安装 npm install webpack webpack-cli -D
)
- 全局安装 css-loader,指令:
npm install css-loader -D
- 全局安装 less-loader,指令:
npm install less-loader -D
- 全局安装 postcss-loader,指令:
npm install postcss-loader -D
- 全局安装 postcss-preset-env,指令:
npm install postcss-preset-env -D
- 全局安装 html-webpack-plugin 插件,指令:
npm install html-webpack-plugin -D
- 全局安装 mini-css-extract-plugin 插件,指令:
npm install mini-css-extract-plugin -D
3、webpack.config.js配置
// 引入 node.js path 核心模块
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 设置 node.js 环境变量 => 默认是生产环境production
process.env.NODE_ENV = 'development'
module.exports = {
mode: 'development',
entry: './src/js/index.js',
output: {
filename: 'js/build.js',
path: resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
/*
css 兼容性处理: postcss => postcss-loader postcss-preset-env
帮 postcss 找到 package.json 中 browserslist 里面的配置,通过配置加载指定的 css 兼容性样式
"browserslist": {
// 开发环境
"development": [
"last 1 chrome version", => 最近的 chrome 浏览器版本
"last 1 firefox version", => 最近的 firefox 浏览器版本
"last 1 safari version" => 最近的 safari 浏览器版本
],
// 生产环境:默认是生产环境,所有需要配置 node 环境变量
"production": [
">0.2%", => 兼容98%以上的浏览器
"not dead", => 排除掉已经摒弃了的浏览器
"not op_mini all"
]
}
*/
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
require('postcss-preset-env')()
]
}
}
]
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader'
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
// 对输出的 css 文件重命名 => 默认的是 main.css
filename: 'css/build.css'
})
],
devServer: {
contentBase: resolve(__dirname, 'build'),
port: 3000,
open: true,
compress: true,
}
}
4、package.json配置
{
"name": "index",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^4.2.2",
"html-webpack-plugin": "^4.4.1",
"less": "^3.12.2",
"less-loader": "^7.0.1",
"mini-css-extract-plugin": "^0.11.0",
"postcss-loader": "^4.0.0",
"postcss-preset-env": "^6.7.0",
"style-loader": "^1.2.1",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production": [
">0.2%",
"not dead",
"not op_mini all"
]
}
}
5、完成配置,使用webpack打包会出现以下报错
解决:postcss-loader下的options下的配置应该写在postcssOptions对象中
错误代码实例
正确代码实例
上一篇: HDRP踩坑记录
下一篇: Swiper Animate动画