一、概念

1.1 现象:

不是马上发起-http-请求获取js文件,而是等一下,或者等到用户需要的时候,发起http请求,获取webpack代码分割的js文件

1.2 创建异步函数

通过函数包裹异步请求模块函数import(),等到需要的时候,在进行http请求,获取对应的js文件

  1. // ....
  2. // 异步代码
  3. function createElement() {
  4. return import(/*webpackChunkName: "lodash"*/ 'lodash')
  5. .then(({ default: _ }) => {
  6. const res = _.join(['test', 'test', 'test'], '-');
  7. const oH1 = document.createElement('h1');
  8. oH1.innerHTML = res;
  9. return oH1;
  10. });
  11. }
  12. // 需要的时候点击,执行函数
  13. // 初始向服务器请求时,不会加载异步文件
  14. // 等到异步函数执行时,从服务器获取对应代码块的文件
  15. document.getElementById('btn').onclick = function () {
  16. createElement().then(div => {
  17. document.body.appendChild(div);
  18. console.log(123);
  19. });
  20. }

QQ录屏20220703151722_.gif

二、Module、chunk、boundle含义

2.1 module:

源码文件中,一个一个的模块,
image.png

2.2 chunk

通过-webpack-将源代码依赖的模块进行打包,分割成一个一个的 代码块—chunk

2.3 boundle

打包后生成的js文件,被看作时是一个一个boundle
image.pngimage.png