webpack还支持一种动态的模块导入方式

清理一下文件并新增一个生产与开发环境及通用配置的webpack.config.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
webpack_learn
|- node_modules
|- package.json
|- webpack.config.js
|- yarn.lock
|- src
|- let.js
|- get.js
|- index.js
|- math.js
|- dist
|- bundle.js
|- index.html

修改config文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');

module.exports = {
entry: {
index: './src/index.js',
- index2: './src/index2.js',
- math: './src/math.js',
},
plugins: [
new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
title: 'Code Splitting'
})
],
- optimization: {
- splitChunks: {
- cacheGroups: {
- commons: {
- name: "commons",
- chunks: "all",
- minChunks: 2
- }
- }
- }
- },
output: {
filename: '[name].bundle.js',
+ chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

然后修改srcindex.js的内容

1
2
3
4
5
6
7
8
9
10
-   import _ from "lodash";
+ function getLodash(){
+ return import(/* webpackChunkName: "lodash" */ 'lodash').then((_)=>{//这里的注释很重要,影响打包后的包名字
+ console.log(_)
+ })
+ }
let name = require('./let.js');
let sayName = require('./get.js');
sayName('大家好,我的名字是'+name)
+ getLodash()

然后执行打包指令

1
npm run build # 或者 yarn build

然后可以看到,文件目录结构变成了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
       webpack_learn
|- node_modules
|- package.json
|- webpack.config.js
|- yarn.lock
|- src
|- let.js
|- get.js
|- index.js
|- math.js
|- dist
+ |- vendors~lodash.bundle.js
|- bundle.js
|- index.html

这样动态引入的lodash就被打包进入了vendors~lodash.bundle.js文件中,从而完成了模块的动态导入