【webpack学习笔记】a07-代码分离

官方文档说进行代码分离有三种方法:

  1. 入口起点:使用entry配置手动分离。
  2. 防止重复:使用CommonsChunkPlugin插件去重合分离chunk

    注:在webpack4中,CommonsChunkPlugin已经被废弃,改用optimization.splitChunks
  3. 动态分离

但是在个人理解: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')
}
}
上一篇:IDEA git修改远程仓库地址


下一篇:BZOJ 3438 小M的作物 & BZOJ 1877 [SDOI2009]晨跑