webpack4升级指南
因为webpack4有很多吸引人的特性,在开发的时候能能提高效率,所以将团队项目的webpack3升级到了webpack4;
新特性
- 对Node.js版本必须>=8.9.4;
- 支持WebAssembly;
- 支持多种模块类型;
- 通过mode来处理开发环境和线上环境优化;
- 更简单配置的拆包功能;
- 更快的热加载功能;
- 零配置模块打包(output:./dist/main.js;entry:./src/index.js);
- 更快的构建时间,大项目及其可观;
- 全新的插件系统,插件优化替换;
插件变化
- nameModulesPlugin => optimization.nameModules;
- noEmitOnErrorsPlugin => optimization.noEmitOnErrors;
- CommonsChunkPlugin => optimization.splitChunks;
- UglifyJsPlugin =>webpack-parallel-uglify-plugin;
- extract-text-webpack-plugin => mini-css-extract-plugin;
开始升级
1、首先我们要将webpack相关的升级到最新的版本,此处是我本次升级的例子
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1",
"webpack-dev-server": "^3.3.1"
2、相关的loader升级一下版本,以下面的Loader为例,其他的请查询文档
"file-loader": "^4.0.0",
"style-loader": "0.23.0",
"url-loader": "1.1.1",
"postcss-loader": "3.0.0",
3、插件升级
"mini-css-extract-plugin": "^0.6.0", // 替代一下抽取样式的 extract-text-webpack-plugin
"string-replace-webpack-plugin": "^0.1.3",
4、升级webpack配置文件,下面是变更了的内容
- css加载开发时期使用style-loader,发布事情使用mini-css-extract-plugin抽取到css文件;
- plugins删除ExtractTextWebpackPlugin,使用MiniCssExtractPlugin代替;
- 根节点添加mode属性,开发时期使用development,发布时期使用production(会有一些优化);
- module节点中使用rules替换loaders,webpack4不支持使用loaders了;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 声明cssloader
const cssLoader = {
test: /\.(css|less)$/,
use: [
'css-loader',
'postcss-loader',
'less-loader'
]
};
// 开发模式使用style-loader
if (!env) {
cssLoader.use.unshift('style-loader');
} else {
cssLoader.use.unshift({
loader: MiniCssExtractPlugin.loader,
options: {hmr: !env, reloadAll: true}
});
}
module.exports = {
mode: env ? 'production' : 'development',
module: {
rules: [
cssLoader
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'assets/[name].css',
chunkFilename: 'assets/[name].[contenthash:8].chunk.css',
})
]
};
参考文档:
- https://webpack.js.org/configuration/#options
- https://webpack.js.org/guides/getting-started/#basic-setup
- https://segmentfault.com/a/1190000014685887
- https://juejin.im/post/5bd03659e51d457aa63a66c8#heading-0
- https://segmentfault.com/a/1190000013608316
- https://www.cnblogs.com/cherryvenus/p/9808320.html
- https://www.jianshu.com/p/7a5f6cffdd87