一、概念
1.1 现象:
不是马上发起-http-请求获取js文件,而是等一下,或者等到用户需要的时候,发起http请求,获取webpack代码分割的js文件
1.2 创建异步函数
通过函数包裹异步请求模块函数import(),等到需要的时候,在进行http请求,获取对应的js文件
// ....// 异步代码function createElement() {return import(/*webpackChunkName: "lodash"*/ 'lodash').then(({ default: _ }) => {const res = _.join(['test', 'test', 'test'], '-');const oH1 = document.createElement('h1');oH1.innerHTML = res;return oH1;});}// 需要的时候点击,执行函数// 初始向服务器请求时,不会加载异步文件// 等到异步函数执行时,从服务器获取对应代码块的文件document.getElementById('btn').onclick = function () {createElement().then(div => {document.body.appendChild(div);console.log(123);});}

二、Module、chunk、boundle含义
2.1 module:
2.2 chunk
通过-webpack-将源代码依赖的模块进行打包,分割成一个一个的 代码块—chunk
2.3 boundle
打包后生成的js文件,被看作时是一个一个boundle

