官方文档说进行代码分离有三种方法:
- 入口起点:使用
entry
配置手动分离。 - 防止重复:使用
CommonsChunkPlugin
插件去重合分离chunk
注:在webpack4中,CommonsChunkPlugin
已经被废弃,改用optimization.splitChunks
- 动态分离
但是在个人理解:2是对1的缺陷补充,所以其实就只有两种分离方法:
- 入口起点手动静态分离
- 动态分离
静态分离:
index.js
import _ from 'lodash';
function component (){
var element = document.createElement('div');
element.innerHTML = _.join(['hello','2019~'], ' ');
return element;
}
document.body.appendChild(component());
another-module.js
import _ from 'lodash';
console.log(
_.join(['Another','module','loadsh!'],' ')
)
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js',
another: './src/another-module.js'
},
devtool: 'inline-source-map',
plugins:[
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Code Splitting',
template: './src/index.html'
})
],
optimization:{
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2
}
}
}
},
output: {
filename: '[name].build.js',
path: path.resolve(__dirname, 'dist')
}
}
动态分离:
index.js
function getComponent(){
return import(/* webpackChunkName:'lodash' */'lodash').then(_ => {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello','2019~'], ' ');
return element;
}).catch(error => 'An error occurred while loading the component');
}
getComponent().then(component => {
document.body.appendChild(component);
})
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'
},
plugins:[
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Code splitting',
template: './src/index.html'
})
],
output:{
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path:path.resolve(__dirname,'dist')
}
}