current position:Home>Webpack learning notes series 07- how it works

Webpack learning notes series 07- how it works

2022-06-24 08:15:55CS Xiaoyao Sword Fairy

webpack Learning notes series 07- working principle

Write By CS Xiaoyao sword immortal My home page : GitHub: Email: [email protected] QQ: 1724338257

1. Basic workflow

  • Preparation stage : establish Compiler and Compilation object . Use the configuration file to merge shell Get initialization parameters by transferring parameters , Instantiate with this parameter Compiler class , And register all plug-ins and bind webpack Life cycle hook.Compiler Is the highest level object in the workflow , Provide global hooks , Inherited from Tapable( That is, the complete event process core class ) , Complete Webpack Environment configuration information , Every Webpack The configuration corresponds to a Compiler object , adopt Tapable Of Hook The mechanism manages the lifecycle of the entire packaging process ;Compilation By Compiler Create an instance object , Also inherit from Tapable , It is the core process of each packaging process , Perform module dependency resolution 、 Optimize resources 、 Rendering runtime Code etc. , Represents a resource version build ,dev-server Next watch It's going to generate new Compilation.
  • Compile phase : complete modules analysis , And generate chunks. call Compiler Class run Method creation Compilation example ,Compilation from entry Start using various loader Processing module , analysis AST Find out each chunk Of modules Dependency relationship , Recursive compilation of dependent modules .
  • Output stage : according to chunks stay output Lower generation bundle file , And results plugin Deal with it as final bundle file . Three steps : Templates Hash to update 、 Template rendering chunk、 Generate the file .

2. Package output code IIFE Function structure

webpack The output code of is based on different configurations , Perform different operations , Spliced template code , For normal packaging ,webpack The packaging product of is a Execute the function expression immediately (IIFE), The function structure is as follows :

(function(modules) {
  	// [1] The module cache  Cache registered modules 
    var installedModules = {};

    // [2] The require function  Module registration method 
  	function __webpack_require__(moduleId) {
        // ...
      	return module.exports;

  	// [3]  Definition  __webpack_require__  Some properties of the function 
  	__webpack_require__.m = modules; // expose the modules object (__webpack_modules__)
  	__webpack_require__.c = installedModules; // expose the module cache
    __webpack_require__.d = function(exports, name, getter) { /* ... */ }; // define getter function for harmony exports
    __webpack_require__.r = function(exports) { /* ... */ }; // define __esModule on exports
    __webpack_require__.t = function(value, mode) { /* ... */ }; // create a fake namespace object
    __webpack_require__.n = function(module) { /* ... */ }; // getDefaultExport function for compatibility with non-harmony modules
    __webpack_require__.o = function(object, property) { /* ... */ }; //
    __webpack_require__.p = ''; // __webpack_public_path__

		// [4]  Pass in  entry  modular , perform  __webpack_require__ , And return the execution result , namely  entry  Of  exports
  	//  Slave entry module  id  Start execution 
    return __webpack_require__((__webpack_require__.s = './src/app.js'));
  	//  Pass all modules in the form of callback parameters , All modules take paths as  key,value  Is similar to  AMD factory  Function of format 
    './src/app.js': function(module, exports, __webpack_require__) {
        const name = __webpack_require__(/*! ./name.js */ './src/name.js');
    './src/name.js': function(module, exports) {
        // name.js
        module.exports = 'Csxiaoyao';

Whole IIFE The core process of the function is divided into four steps :

  1. Define the object that holds the registered module installedModules;
  2. Define module load function __webpack_require__;
  3. Definition __webpack_require__ Some properties of the function ;
  4. perform __webpack_require__ function , Pass in entry modular , And return the execution result , namely entry Of exports object

The IIFE The passed parameter of the function is modules object ,key Is the file path ,value Is similar to AMD factory Function of format .

3. __webpack_require__ function

3.1 Function overview

The function is webpack At the heart of , Responsible for calling and registering modules :

//  Cache registered modules 
var installedModules = {};
//  Accept module id As a parameter 
function __webpack_require__(moduleId) {
    // 1.  Judge whether it is registered or not 
    if (installedModules[moduleId]) {
        return installedModules[moduleId].exports;
    // 2.  Register the module and cache 
    var module = (installedModules[moduleId] = {
        i: moduleId, //  modular  id
        l: false, // loaded, Whether the... Has been loaded  flag
        exports: {} //  Output object of the module 
    // 3.  perform  IIFE  Of the incoming module  factory  function , The context is  module.exports
  	// 		 At the same time the incoming 3 Parameters : Module itself 、 modular  exports  object 、__webpack_require__  function 
    modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
    // 4.  to update  flag  Indicates that the module has been registered and loaded 
    module.l = true;
    // 5.  Return module  exports  Object as output 
    return module.exports;

3.2 Use call Method to execute the factory function

IIFE Incoming modules object ,key Is the module path ,value Is similar to AMD factory Function of format :

function(module, exports, __webpack_require__) {
    const name = __webpack_require__('./src/name.js');

factory Of 3 Each parameter corresponds to __webpack_require__ Function call Incoming 3 Parameters , And context this namely this It's incoming module.exports namely exports object .

3.3 __webpack_require__ Add attribute

__webpack_require__.s:  Record the... Of the entry file  moduleId
__webpack_require__.m:  All module objects , namely  IIFE  Function passed in  modules  Parameters 
__webpack_require__.c:  namely  installedModules  Cache object 
__webpack_require__.d:  Used to get  ES modules, Output value references 
__webpack_require__.r:  to  exports  Definition  __esModule  attribute 
__webpack_require__.t:  do  ES module default  and  CommonJS module  compatible 
__webpack_require__.n:  Unified  ES module / CommonJS module  Export format , namely ES Module return module['default']
__webpack_require__.o:  Judge a Object Is there a property attribute ,
__webpack_require__.p:  Corresponding to  output.publicPath, namely  __webpack_public_path__

copyright notice
author[CS Xiaoyao Sword Fairy],Please bring the original link to reprint, thank you.

Random recommended