生产环境需要处理的内容
1、css从js中提取出来(避免创建style标签闪屏,加载慢)
2、提高性能,压缩
3、处理样式和js兼容
================提取css样式==============
使用插件mini-css-extract-plugin 注意版本是0.9.0
build下面的index.html会增加
<link href="main.css" rel="stylesheet"></head>
重点:
loader中
use:[
//取代style-loader,将js中的css提取成单独文件,写法不同
MiniCssExtractPlugin.loader,
'css-loader'
]
plugins中
new MiniCssExtractPlugin({
//filename对输出的文件进行重命名
// filename: '[name].css',//原文件名字
filename: 'css/h.css',//原文件名字
})
=================css兼容性处理==============
post-css 是使用 JS 插件来转换 CSS 的工具
loader:postcss-loader postcss-preset-env
注意安装版本号
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
webpack.config.js代码如下
const {resolve} = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
//设置node.js的环境变量
// process.env.NODE_ENV = 'production';
module.exports = {
entry:'./src/js/index.js',
output:{
filename:'js/out.js',
path:resolve(__dirname,"build")
},
module:{
rules:[
{
test:/\.css$/,
use:[
//取代style-loader,将js中的css提取成单独文件,写法不同
MiniCssExtractPlugin.loader,
'css-loader',
//处理css兼容性
//使用loader的默认配置
// 'postcss-loader',
//修改loader的配置
{
loader:'postcss-loader',
options:{
ident:'postcss',
//使用哪些插件
plugins:()=>[
//postcss-preset-env插件作用帮postcss找到package.json中browserlist里面的配置
//通过配置加载指定的兼容性样式
require('postcss-preset-env')()
]
}
}
]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new MiniCssExtractPlugin({
//filename对输出的文件进行重命名
// filename: '[name].css',//原文件名字
filename: 'css/h.css',//原文件名字
})
],
mode:'development',
}
package.json中代码如下:
{
"name": "webp-test",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^5.0.1",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.0",
"html-withimg-loader": "^0.1.16",
"less": "^3.12.2",
"less-loader": "^7.1.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^5.0.0",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"sass-loader": "^10.1.0",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1",
"webpack": "^4.32.2",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.5.1"
},
"dependencies": {},
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firfox version",
"last 1 safari version"
],
"production": [
">0.01%",
"not dead",
"not op_mini all"
]
}
}