返回
多页应用 Webpack4 配置及优化记录
前端
2023-10-26 01:53:51
Webpack4 多页应用配置
项目结构
├── app
│ ├── pageA
│ │ ├── index.js
│ │ └── index.html
│ ├── pageB
│ │ ├── index.js
│ │ └── index.html
│ └── common
│ └── util.js
├── node_modules
├── package.json
├── webpack.config.js
└── index.html
配置文件
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
pageA: './app/pageA/index.js',
pageB: './app/pageB/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js'
},
plugins: [
new HtmlWebpackPlugin({
template: './app/pageA/index.html',
filename: 'pageA.html',
chunks: ['pageA']
}),
new HtmlWebpackPlugin({
template: './app/pageB/index.html',
filename: 'pageB.html',
chunks: ['pageB']
})
]
};
优化建议
代码分割
代码分割是将项目中的代码分成多个块,然后按需加载。这可以提高页面的加载速度,因为浏览器只需要加载当前页面所需的代码块。
Webpack4 中可以使用以下方法实现代码分割:
- 使用
import()
动态导入模块 - 使用
require.ensure()
动态导入模块 - 使用
webpack.optimize.SplitChunksPlugin
插件
Tree shaking
Tree shaking 是指删除未使用代码的过程。这可以减少包的大小,提高性能。
Webpack4 中可以使用以下方法实现 tree shaking:
- 使用 ES6 模块语法
- 使用
webpack.optimize.UglifyJsPlugin
插件
缓存
缓存可以提高页面的加载速度,因为浏览器可以从缓存中加载资源,而无需重新下载。
Webpack4 中可以使用以下方法实现缓存:
- 使用
webpack.optimize.CommonsChunkPlugin
插件 - 使用
webpack.optimize.AggressiveMergingPlugin
插件
性能
性能优化是提高页面加载速度的重要手段。
Webpack4 中可以使用以下方法优化性能:
- 使用
webpack.DefinePlugin
插件定义变量 - 使用
webpack.DllPlugin
插件预编译模块 - 使用
webpack.HotModuleReplacementPlugin
插件实现热更新
踩坑记录
入口文件配置错误
在配置入口文件时,可能会遇到以下错误:
ERROR in Entry module not found: Error: Can't resolve './app/pageA/index' in '.../app'
这是因为入口文件的路径不正确。请确保入口文件的路径正确。
HtmlWebpackPlugin 配置错误
在配置 HtmlWebpackPlugin 时,可能会遇到以下错误:
ERROR in Entry module not found: Error: Can't resolve './app/pageA/index' in '.../app'
这是因为 HtmlWebpackPlugin 的 template
参数不正确。请确保 template
参数指向正确的 HTML 文件。
代码分割配置错误
在配置代码分割时,可能会遇到以下错误:
ERROR in Entry module not found: Error: Can't resolve './app/pageA/index' in '.../app'
这是因为代码分割的配置不正确。请确保代码分割的配置正确。