Webpack engineering practice summary of webpack core modules, Compiler and Compilation, basic process and HMR

One, webpack core module

  1. WebpackProject is enormous, but it Webpackis essentially a mechanism for the flow of events. A variety of plug flow in series through the event, which eventually complete Webpackthe core of the whole process, and the realization of the event flow mechanism is Tapablethe module. WebpackResponsible for compilation Compilerand creation Bundleof Compilationare inherited from Tapable.
  2. WebpackCore Library Tapableprinciple and EventEmitteris similar to, but more powerful, including a variety of types, by registering and monitoring events trigger Webpackfunction method lifecycle. In the Webpackmiddle, tapablethey are put objects hookson, so we call them hook
  3. TapableThe principle analysis, Tapablethe execution process can be divided into four steps:
  • Use tap*of the event to register binding. Depending on the type of binding offers three ways: tap、tapPromise、tapAsyncin which tapPromise、tapAsyncasynchronous type Hookbinding method;
  • Use call*the event triggering, depending on the type, but also provides three ways to trigger:call、promise、callAsync;
  • Generate code snippets of the corresponding type (the code to be executed is actually spelled out by spelling strings);
  • Generate the code fragment generated in the third step.
  1. Summary: Tapableis Webpackthe core module Webpackof all work processes are through Tapableto achieve. TapableEssentially provides a variety of types of event binding mechanism, you can choose different types of characteristics according to different processes Hookused. TapableThe core implementation stage in the binding event with our usual custom JavaScriptevent binding (for example EventEmitter) is not much difference, but when events trigger the execution of the function temporarily generates code snippets that can be executed. In this implementation, Tapableto achieve a strong ability to control the flow of events, also increased as waterfall/parallelthe series method to achieve the ability to control asynchronous / parallel events such as streams.

2. Webpack's Compiler and Compilation

  1. In the Webpackworkflow, Compilerand Compilationare inherited from Tapable, a different point is Compilerthat each Webpackconfiguration corresponding to an Compilerobject, record the entire Webpacklife cycle; during the construction of each construct generated every Compilation,Compilationis a product of the build cycle.
  2. Summary: Webpackin two core classes Compilerand Compilation. CompilerEach time Webpackthe object of all life cycle, and Compilationis Webpackthe life cycle of the object each time the build process, Compilationthrough the Compilerinstance created. Both classes have their own life cycle that is different from their own Hook, by adding the corresponding Hookevent, you can get the life cycle of each key data and objects. CompilationThere is a very important subject is Statsthe object, the object can be obtained by Webpackall the packaged module、chunk 和 assetsinformation, through the analysis Statscan get a lot of useful information objects, such as webpack-bundle-analyzerthis type of analysis packaged plug-ins are the result of the analysis Statsto get the analysis report objects.

Three, the basic process of Webpack

  1. Webpack The basic process can be divided into three stages, as follows:
  • Preparation phase: The main task is to create Compilerand Compilationobjects;
  • Compilation phase: This phase is to complete the task modulesparsing and generation chunks;
  • moduleAnalysis: Contains three main steps, creating an instance, loadersapplication and dependency collection;
  • chunksGenerating, for each major step is to find the chunkneed to include modules.
  • Output stage: The main task at this stage is based on chunksgenerating the final document,
  1. In the output stage, there are three main steps: template Hashupdate, template rendering chunk, generated files. Refined to the specific code level, it can be roughly divided into:
  • Initialization parameters include: from the configuration file and shellreading and combination parameters, and then obtain final parameters;
  • shell The parameters in are better than those in the configuration file;
  • Obtained in the previous step using the parameters of an instance of Compilerthe class, all the registered plug-ins, to the corresponding Webpackbuild lifecycle bindings Hook;
  • Start the compilation: the implementation of Compilerthe class runmethod to begin compiling;
  • compiler.runMethod call compiler.compile, in compilethe instance of a Compilationclass.
  1. Compilation It is to build and package things, the main things include:
  • Find Entrance: According to entrythe configuration, find out all entry documents;
  • Compiling module: based on the file type and loaderconfiguration, using the corresponding loaderfile conversion processing is performed;
  • Parsing file ASTsyntax tree;
  • Find out file dependencies;
  • Recursively compile dependent modules.
  1. After the final result of each recursion file, according to entrythe configuration of code generating block chunk;
    output of all chunkto the corresponding outputpath.
  2. shellThe parameters in is better than the configuration file. For example: the configuration file specifies modeis development, while shellin the incoming --mode production, then the final modevalue production.
  3. In the Webpackworkflow, the Tapableruns through them, Tapableall kinds of Hook(hook) make up the Webpacklife cycle. Tapable HookThe relationship with the life cycle is:
  • Hook: Hook, corresponding to Tapablethe Hook;
  • Life Cycle: WebpackThe flow of execution, the hook is in fact a life cycle similar to the general entryOption's Hook, in the life cycle entry-option.
  • Participation in Webpacktwo important modules process is: Compiler和Compilation.
  1. Summary: Webpackpacking process starts to read the configuration file from, respectively, after the preparation stage, modulesthe output stage, the chunksoutput stage and bundleoutput stage of the property. In each stage, each with a different "roles" to participate, the entire Webpackpackaging process is through Compilercontrolled, and each is packaged process through Compilationcontrolled. In normal mode, packaged, webpackthe Compilerand Compilationis one to one relationship; watchmode, Webpackit is Compilerbecause file changes result in multiple packaging process, so Compiler, and Compilationis to-many relationship, through Hook Compilerthe process, you can get a callback every packaging process .

  2. Webpack The classes in the workflow are as follows:

  • Tapbale: The Webpackcore class of event flow;
  • Compiler: WebpackWorkflow highest level object, initial configuration, provides Webpackglobal hook processes, such as done、compilationsuch;
  • Compilation: By the Compilerinstance of the object is created, and each package is the core of the process flow, be resolved within the object module dependencies, resource optimization, rendering runtimethe code and other things, the following in Compilationsome objects there are used:
    • Resolver: Analyze (module)、loaderpaths such as modules to help find the corresponding location;
    • ModuleFactory: Responsible for module configuration example, the Resolverresolution succeeds components in the source code read from the file out, and then create a module object;
    • Template: Mainly to generate runtimethe code, the code is parsed in accordance with the following dependency order processing, put on Templatewhat we finally packed up code.

Four, HMR in webpack

  1. HMR The whole cycle is divided into two parts: the start-up phase and the file monitoring and updating process.
  2. In the start-up phase, Webpackand webpack-dev-serverinteract. WebpackAnd webpack-dev-servermainly through Expressmiddleware webpack-dev-middlewareto interact, this stage can be subdivided into the following steps:
  • webpack-dev-serverStart Webpackpackaged watchmode, in this mode Webpackwill monitor file changes, once a file is changed, it will re-packaged, watchmode Webpackpacked result will not drop the disk (saved to the hard disk);
  • webpack-dev-serverBy webpack-dev-middlewarethe Webpackinteraction, Webpack-dev-middlewareinitialization receiving Webpackthe Compilerobject, Compilerthe hook can monitor Webpackthe packaging process;
  • If devServer.watchContentBase=true, then webpack-dev-serverchange the monitor static files folder, change the notification browser to refresh the page again to request a new file;
  • After opening the browser webpack-dev-serverwill use sockjsthe browser and Serverbetween create a WebSocketlong connection, this connection is long and browser webpack-dev-servercommunication bridges, communication between them is the main content is to pass the file information (compiled module hashvalue), if this time Webpackmonitor file modification occurred, webpack/hot/dev-serverto achieve HMRupdate or refresh the page.
  1. Note that as follows:
  • webpack-dev-serverThe contentBasecan be understood as a static resource directory on the server folder, start serverlater, you can access specific documents to a URL method + computer file path, file with the Webpackpackage out of the path are not the same;
  • There are two monitoring file changes, the first step in the Webpackmonitoring of the entire module dependencies changes, changes in the re-start Webpackcompile; the third step in webpack-dev-servertheir own monitoring contentBasefile changes, the file tells the browser to refresh the page changes, there is not refresh the page HMR, because contentBasethe content of non- Webpackpackaged dependencies.
  • WebSocketNeed server and browser has created a corresponding connection code (new WebSocket),webpack-dev-serverin a browser by chunksinserting in webpack-dev-server/clientthis file to create WebSocketa communication.
  1. Start end of this phase, when Webpackafter monitoring file changes, this time into the file update process monitoring, when Webpackafter a file to monitor changes in the dependency graph:
  • WebpackWill re-compile the file, this time we webpack.config.jsadd plug-ins HotModuleReplacementPluginwill generate a list of differences between two files compiled (manifest)file [hash].hot-update.json, this manifest JSONfile contains the change file Updatecontents, that is [id].[hash].hot-update.js. webpack-dev-serverThe webpack-dev-middlerwill pass Webpackthe Compilerhook listening packing process, and then inform the webpack-dev-serveruse WebSocketlong connection push after compiling hashvalue;
  • In addition to sending compiled Hashvalue outside, webpack-dev-serverbut also through the long connection tells the browser to the current page code is invalidthe state, need to update the new code;
  • The browser to get Hashafter, will first initiate a Ajaxrequest manifestfile [hash].hot-update.jsoncontents of the file;
  • manifestAfter the contents of the file list to get, will tell HMRof Runtimethose requests change JavaScriptfile, this time will Runtimebe initiated in accordance with the inventory list JSONPrequest, the two compiled a difference file [id].[hash].hot-update.jsget down into the page headlabel scriptin execution, finally completed a full update Process.
  1. Summary: webpack-dev-serverAlthough it can be started directly HMR, the real core is webpack-dev-middleware. webpack-dev-serverIn addition to this middleware, the main function is a static server.

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/110507675