After reading the webpack source code, I learned these

https://developpaper.com/after-reading-the-webpack-source-code-i-learned-these/

Time:2020-8-27
 

After reading the webpack source code, I learned these

After react, Vue, this is the third front-end project that focuses on reading source code – webpack. This paper mainly focuses on the following aspects:

  • Why: why look at webpack source code
  • How: how to read webpack source code
  • What: what did you learn after reading the source code

Three directions.

Welcome to star and subscribe to my blog.

WHY

It is true that webpack is a front-end engineering tool, easy to understand and easy to use. It seems that there is no need for in-depth study. Why bother to read the source code? This, I am writing this article also asked. When making the outline, I think why is the best to write, and a few words can be used. However, it has been proved that it is worth mentioning that it is really necessary to be more serious.
Guess the possible motivation of the webpack source code partner without authorization:

  1. Rich working experience
  2. Technology really loves powder, know how it is, and learn how to do it
  3. Work or personal project related, reference learning
  4. See someone write related articles, also look to understand

The first reason for the author is 4, then 1, 2. Of course, 1, 2 should be the motivation of most people to look at the source code of the project.

How

Build source debugging environment

To read the source code, first get the source code, and then finally be able to read while debugging. Of course, if your intelligence and reasoning skills are amazing, you can read them online directly on GitHub.
There are two ways to download the source code. One is the most common git clone. The clone of the webpack project on GitHub is transferred locally. After pull, it is consistent with the latest official webpack code, once and for all. However, when the author tries the first method, the clone does not come down. It is likely that the webpack source file is too large and the GitHub server clone is always slow.
The second method is to download the release version of webpack source code. Select a webpack source version you want to read and download “source code (zip)” directly. It’s very fast because it doesn’t contain. GIT.
After reading the webpack source code, I learned these

IDE authors use vscode to debug node easily. After getting the source code, create a new folder in the directory, write a simple webpack case, and then use vscode for debugging.
However, in practice, you can directly use the webpack.js Debugging may cause errorsCannot find module 'json-parse-better-errors'orCannot find module 'webpack/lib/RequestShortener', just runnpm install webpack webpack-cli --save-devTo solve the error, and does not affect the debugging source code.

After reading the webpack source code, I learned these

This attachment uses the version reference when debugging. After downloading, use vscode to open webpack-4.41.4 (modified), install dependencies, install webpack and webpack cli, and press F5 to start debugging.

Debug and clarify the general trend of pulse path

Webpack has a large amount of source code, so it is unnecessary to read every line of code. However, we should at least know its overall running process, the core code repeatedly used, and the life cycle of each module.

Find the source code of core functions

Due to the large amount of code, it is very difficult to find the source code of the core function when going through the overall process, at least for the webpack source code, because of its unique plug-in and callback structure.
However, we can find and read the relevant source code separately according to each core function we want to know. For example, if we want to see how webpack is packaged and generated bundle.js You can call nodejs file system output file method through webpack to search “WriteFile” globally to find relevant code, or bundle.js Search for the keyword “/ / check if module is in cache”.

After reading the webpack source code, I learned these

What

Through debugging and reading the code, we can understand the overall trend of the code and how to package and generate webpack bundle.js The author learned the following contents:

  • Tapable plug-in mechanism
  • Simplified webpack running process
  • bundle.js How to generate content

Tapable

Tapable is widely used in source code. To understand the source code, you must first learn the mechanism of tapable. In fact, it is not complicated, and we only need to know its basic function and usage.
Tapable can be understood as a set of hook callback function mechanism. Each hook can subscribe to multiple functions. When a hook is published, the hook will run to subscribe to multiple functions.
It is illustrated by a simple case.

const { SyncHook } = require('tapable')
class Car {
    constructor() {
        this.hooks = {
           //Add a hook
            start: new SyncHook()
        }
    }
}
const car = new Car()
//The start hook subscribes to a function
car.hooks.start.tap( 'run slowly', () => console.log('start running slowly')  )
//The start hook subscribes to another function
car.hooks.start.tap( 'run mediumly', () => console.log('start running mediumly') )

//Publish hook
car.hooks.start . call() // output: run slowly run mediumly

Simplified webpack running process

After reading the webpack source code, I learned these

bundle.js How to generate content

Uncompressed bundle.js The file structure is generally as follows:

/******/ (function(modules) { // webpackBootstrap
/******/     // The module cache
/******/     var installedModules = {};
/******/
/******/     // The require function
/******/     function __webpack_require__(moduleId) {
/******/
/******/         // Check if module is in cache
/******/         if(installedModules[moduleId]) {
/******/             return installedModules[moduleId].exports;
/******/         }
/******/         // Create a new module (and put it into the cache)
/******/         var module = installedModules[moduleId] = {
/******/             i: moduleId,
/******/             l: false,
/******/             exports: {}
/******/         };
....

So how does webpack generate this content?
In fact, webpack has two steps to process the content. The first step is to generate the combined JS code through the loader (the default is Babel loader). The second step is to put the combined JS code into the default webpack function to avoid variable disclosure.
If before packing:
foo.js

export const foo = () => 'hello foo!'

bar.js

import { foo } from './foo.js'
foo()
console.log( 'hello bar!' )

The first step of packaging is to generate the combined JS code through loader (the default is Babel loader)

...
const foo = () => 'hello foo!'
...
\r\n__WEBPACK_MODULE_REFERENCE__0_666f6f_call__()\r\nconsole.log( 'hello bar!' )
...

In the second step of packaging, combine JS code into the default function of webpack.

/******/ (function(modules) { // webpackBootstrap\n
...
const foo = () => 'hello foo!'
...
foo()
console.log( 'hello bar!' )
...

It is worth noting that the core document isConcatenatedModule.jsBy traversingmodulesWithInfoThe package code is generated.

common problem

1 . runtimeWhat is it?

Whether in webpack source code, Vue source code and other places, runtime often appears. What is runtime?
After repeatedly consulting the data and deliberation, the runtime code can be understood as the code generated after compilation. For example, for react, the runtime code is the JS code generated after compiling the JSX code. For Vue, the runtime code is JS code generated after compiling template, script and style.

2. How to implement hot update, code splitting and tree shaping?

Webpack has a lot of content and core module principles, such as how to operate loader, how to implement code splitting, and how to achieve tree shaping and hot loading. But after all, time is limited. The goal of reading the source code is not to understand all the contents, but to master the main operation process of webpack and several modules of interest. Therefore, other module principles will be added to this paper. Partners who are interested in the corresponding modules can search the relevant content online first.

Read the source Resource Recommendation

  • how-react-works.pdf
  • Webpack: Wu Haolin
  • help developers better understand how webpack works: artsy-webpack-tour
  • build your own webpack

Thank you for taking the time to read this article. If you like this article, welcome to like, collect and share, let more people see this article, this is also my greatest encouragement and support!
Welcome to star and subscribe to my original front end technology blog.

 
posted on 2021-02-04 18:29  bowen_tong  阅读(139)  评论(0)    收藏  举报