代码分离
代码分离是 webpack 中引人注目的特性之一。此特性能够把代码分离到不同的 bundle 中,然后可以按需加载或并行加载这些文件。代码分离可以用于获取更小的 bundle , 以及控制资源加载优先级,如果使用合理,会极大影响加载时间
有三种常用的代码分离方法:
(1)入口起点:使用 entry 配置手动分离代码
(2)防止重复:使用 CommonsChuckPlugin 去重和分离 chunk
(3)动态导入:通过模块的内联函数调用来分离代码
入口起点
是迄今为止最简单,最直观的分离代码的方式。不过这种方式手动配置较多,有一些坑
|- package.json
|- webpack.config.js
|- /dist
|- /src
|- index.js
+ |- another-module.js
|- /node_modules
another.js
import printMe from './print'
window.onload = function () {
printMe()
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
entry : {
index : './src/index.js',
another : './src/another.js'
},
output: {
filename: "[name].bundle.js",
path : path.resolve(__dirname,'dist')
},
plugins: [
new HtmlWebpackPlugin({
template : './src/index.html'
}),
new CleanWebpackPlugin(['dist'])
],
module: {
rules : [
{
test : /\.css$/,
use : ['style-loader','css-loader']
},
{
test : /\.(png|jpg)$/,
use : ['file-loader']
}
]
}
}
正如前面提到的,这种方法存在一些问题:
(1)如果入口 chunks 之间存在包含重复的模块,那些重复模块都会被引入到各个 bundle 中
(2)这种方法不够灵活,并且不能将核心应用程序逻辑进行动态拆分代码
重复引用通过使用 CommonsChunkPlugin 来移除重复的模块
防止重复
CommonsChunkPlugin 插件可以将公共的依赖模块提取到已有的入口 chunk 中,或者提取到一个新生成的 chunk 。(CommonsChunkPlugin 已经从 webpack 4+ 中移除)