此特性能夠把代碼分離到不同的 bundle 中堕战,然后可以按需加載或并行加載這些文件。代碼分離可以用于獲取更小的 bundle拍霜,以及控制資源加載優(yōu)先級嘱丢,如果使用合理,會極大影響加載時間祠饺。
有三種常用的代碼分離方法:
- 入口起點:使用 entry 選項手動分離代碼越驻。
- 防止重復:使用 CommonsChunkPlugin 去重和分離 chunk。
- 動態(tài)導入:通過模塊的內(nèi)聯(lián)函數(shù)調用來分離代碼道偷。
entry
將js分割為多個缀旁,利用瀏覽器多線程,同時加載多個js文件勺鸦,以此來提升效率并巍,但同時此方法也將帶來坑,會將重復的模塊都打包换途。需要結合CommonsChunkPlugin來去重復懊渡。
image.png
app.js
import _ from 'lodash';
console.log('Hello app module');
main.js
import _ from 'lodash';
console.log('Hello main module');
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
main: './src/main.js',
app: './src/app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
title: '代碼分離'
}),
],
devServer: {
contentBase: './dist'
}
}
image.png
image.png
兩個模塊都將lodash打包了,導致重復代碼军拟,文件過大剃执。
分離重復代碼
在entry分離的步驟中,增加插件CommonsChunkPlugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
main: './src/main.js',
app: './src/app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
title: '代碼分離'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
})
],
devServer: {
contentBase: './dist'
}
}
image.png
動態(tài)導入
使用ES6語法import導入或者使用webpack提供的require.ensure.
image.png
app.js
let button = document.createElement('button');
button.innerHTML = '點我';
button.onclick = () => {
import(/* webpackChunkName: "lodash" */ 'lodash').then(function(_){
console.log(_.join(['Hello', 'webpack'], ' '));
}).catch(function(error){
console.error('error', error);
});
}
document.body.appendChild(button);
通過注釋指明模塊的名字 /* webpackChunkName: "lodash" */
webpack.config.js
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Dy import'
})
]
}
當點擊按鈕后才請求lodash模塊
image.png