Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello, I’m Shanyue.

This is my front end engineering knowledge card collection 4/36 published in Denver

A Webpack runtime includes two of the most important data structures:

  1. __webpack_modules__Maintains an array of all modules. The entry module is parsed into an AST, all modules are searched first based on the DEPTH of the AST, and this module array is constructed. Each module has a wrapping function(module, module.exports, __webpack_require__)Package the module.
  2. __webpack_require__(moduleId): Manually implements loading a module. Cache loaded modules and locate unloaded modules according to their IDS__webpack_modules__Executes and returns the wrapped function inmodule.exportsAnd cache.

In Webpack, code spliting is implemented through import().

import('./sum').then(m= > {
  m.default(3.4)})// The following is the contents of sum.js
const sum = (x, y) = > x + y
export default sum
Copy the code

When you load data using import(), the above code is compiled by Webpack into the following code

__webpack_require__.e(/* import() | sum */ 644).then(__webpack_require__.bind(__webpack_require__, 709)).then(m= > {
  m.default(3.4)})Copy the code

The code for each chunk is as follows. The following is the chunk constructed by the sum function:

"use strict";
(self["webpackChunk"] = self["webpackChunk"] || []).push([[644] and {/ * * * / 709:
/ * * * / ((__unused_webpack_module, __webpack_exports__, __webpack_require__) = > {

        __webpack_require__.r(__webpack_exports__);
        /* harmony export */ __webpack_require__.d(__webpack_exports__, {
        /* harmony export */   "default": () = > (__WEBPACK_DEFAULT_EXPORT__)
        /* harmony export */ });
        const sum = (x, y) = > x + y

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (sum);


/ * * * /}}));Copy the code

The following two data structures are key to loading chunk:

  1. __webpack_require__.e: Loads chunk. For example, 644 is chunkId. This function will use JSONP (document.createElement('script')Load chunk asynchronously and encapsulate it as a Promise.
  2. self["webpackChunk"].push: JSONP cllaback, collect modules, such as 709 is the ID of the sum module. This function places 709__webpack_modules__In the.

In fact, output.chunkloading can be configured in Webpack to select how chunk is loaded

webpack({
    entry: './index.js'.mode: 'none'.output: {
      filename: 'main.[contenthash].js'.chunkFilename: '[name].chunk.[chunkhash].js'.path: path.resolve(__dirname, 'dist/import'),
      clean: true.// The default is' jsonp '
      chunkLoading: 'import'}})Copy the code

See the implementation of loading a chunk in the sample Webpack runtime code.