【webpack學習筆記】a07-程式碼分離
阿新 • • 發佈:2019-01-09
官方文件說進行程式碼分離有三種方法:
- 入口起點:使用
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')
}
}