Webpack 4 踩坑指南

Update to Webpack 4

yarn upgrade webpack

同时升级相关 loader 依赖

(or)Install Webpack 4

yarn add webpack webapck-dev-server webpack-merge webpack -cli

启动项目

对原配置未做修改情况下,启动项目,启动信息会有 4 个 Warning 提示:

1
2
configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
1
2
asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
1
entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
1
2
webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.

解决方法:在配置中添加 mode 属性:

webpack4 中需要配置mode参数

开发环境

1
2
3
4
5
{
...
mode: 'development'
...
}

生产环境

1
2
3
4
5
{
...
mode: 'production'
...
}

或者

1
2
3
4
5
{
...
mode: process.env.NODE_ENV
...
}

重新启动项目,警告消失

目测启动速度更快,暂未做相关测试

CommonsChunkPlugin

webpack 4 移除 CommonsChunkPlugin 插件

通过配置 ptimization 可实现 CommonsChunkPlugin 功能,同时,vendor 不需要配置,同样可以在 ptimization 中配置

1
2
3
4
5
6
ptimization: {
splitChunks: {
chunks: 'all
},
runtimeChunk: true
}