One, webpack core module
Webpack
Project is enormous, but itWebpack
is essentially a mechanism for the flow of events. A variety of plug flow in series through the event, which eventually completeWebpack
the core of the whole process, and the realization of the event flow mechanism isTapable
the module.Webpack
Responsible for compilationCompiler
and creationBundle
ofCompilation
are inherited fromTapable
.Webpack
Core LibraryTapable
principle andEventEmitter
is similar to, but more powerful, including a variety of types, by registering and monitoring events triggerWebpack
function method lifecycle. In theWebpack
middle,tapable
they are put objectshooks
on, so we call them hookTapable
The principle analysis,Tapable
the 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、tapAsync
in whichtapPromise、tapAsync
asynchronous typeHook
binding 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.
- Summary:
Tapable
isWebpack
the core moduleWebpack
of all work processes are throughTapable
to achieve.Tapable
Essentially provides a variety of types of event binding mechanism, you can choose different types of characteristics according to different processesHook
used.Tapable
The core implementation stage in the binding event with our usual customJavaScript
event binding (for exampleEventEmitter
) is not much difference, but when events trigger the execution of the function temporarily generates code snippets that can be executed. In this implementation,Tapable
to achieve a strong ability to control the flow of events, also increased aswaterfall/parallel
the series method to achieve the ability to control asynchronous / parallel events such as streams.
2. Webpack's Compiler and Compilation
- In the
Webpack
workflow,Compiler
andCompilation
are inherited fromTapable
, a different point isCompiler
that eachWebpack
configuration corresponding to anCompiler
object, record the entireWebpack
life cycle; during the construction of each construct generated everyCompilation,Compilation
is a product of the build cycle. - Summary:
Webpack
in two core classesCompiler
andCompilation
.Compiler
Each timeWebpack
the object of all life cycle, andCompilation
isWebpack
the life cycle of the object each time the build process,Compilation
through theCompiler
instance created. Both classes have their own life cycle that is different from their ownHook
, by adding the correspondingHook
event, you can get the life cycle of each key data and objects.Compilation
There is a very important subject isStats
the object, the object can be obtained byWebpack
all the packagedmodule、chunk 和 assets
information, through the analysisStats
can get a lot of useful information objects, such aswebpack-bundle-analyzer
this type of analysis packaged plug-ins are the result of the analysisStats
to get the analysis report objects.
Three, the basic process of Webpack
Webpack
The basic process can be divided into three stages, as follows:
- Preparation phase: The main task is to create
Compiler
andCompilation
objects; - Compilation phase: This phase is to complete the task
modules
parsing and generationchunks
; module
Analysis: Contains three main steps, creating an instance,loaders
application and dependency collection;chunks
Generating, for each major step is to find thechunk
need to includemodules
.- Output stage: The main task at this stage is based on
chunks
generating the final document,
- In the output stage, there are three main steps: template
Hash
update, template renderingchunk
, generated files. Refined to the specific code level, it can be roughly divided into:
- Initialization parameters include: from the configuration file and
shell
reading 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
Compiler
the class, all the registered plug-ins, to the correspondingWebpack
build lifecycle bindingsHook
; - Start the compilation: the implementation of
Compiler
the classrun
method to begin compiling; compiler.run
Method callcompiler.compile
, incompile
the instance of aCompilation
class.
Compilation
It is to build and package things, the main things include:
- Find Entrance: According to
entry
the configuration, find out all entry documents; - Compiling module: based on the file type and
loader
configuration, using the correspondingloader
file conversion processing is performed; - Parsing file
AST
syntax tree; - Find out file dependencies;
- Recursively compile dependent modules.
- After the final result of each recursion file, according to
entry
the configuration of code generating blockchunk
;
output of allchunk
to the correspondingoutput
path. shell
The parameters in is better than the configuration file. For example: the configuration file specifiesmode
isdevelopment
, whileshell
in the incoming--mode production
, then the finalmode
valueproduction
.- In the
Webpack
workflow, theTapable
runs through them,Tapable
all kinds ofHook
(hook) make up theWebpack
life cycle.Tapable Hook
The relationship with the life cycle is:
Hook
: Hook, corresponding toTapable
theHook
;- Life Cycle:
Webpack
The flow of execution, the hook is in fact a life cycle similar to the generalentryOption
'sHook
, in the life cycleentry-option
. - Participation in
Webpack
two important modules process is:Compiler和Compilation
.
-
Summary:
Webpack
packing process starts to read the configuration file from, respectively, after the preparation stage,modules
the output stage, thechunks
output stage andbundle
output stage of the property. In each stage, each with a different "roles" to participate, the entireWebpack
packaging process is throughCompiler
controlled, and each is packaged process throughCompilation
controlled. In normal mode, packaged,webpack
theCompiler
andCompilation
is one to one relationship;watch
mode,Webpack
it isCompiler
because file changes result in multiple packaging process, soCompiler
, andCompilation
is to-many relationship, throughHook Compiler
the process, you can get a callback every packaging process . -
Webpack
The classes in the workflow are as follows:
Tapbale
: TheWebpack
core class of event flow;Compiler
:Webpack
Workflow highest level object, initial configuration, providesWebpack
global hook processes, such asdone、compilation
such;Compilation
: By theCompiler
instance of the object is created, and each package is the core of the process flow, be resolved within the object module dependencies, resource optimization, renderingruntime
the code and other things, the following inCompilation
some objects there are used:Resolver
: Analyze(module)、loader
paths such as modules to help find the corresponding location;ModuleFactory
: Responsible for module configuration example, theResolver
resolution succeeds components in the source code read from the file out, and then create a module object;Template
: Mainly to generateruntime
the code, the code is parsed in accordance with the following dependency order processing, put onTemplate
what we finally packed up code.
Four, HMR in webpack
HMR
The whole cycle is divided into two parts: the start-up phase and the file monitoring and updating process.- In the start-up phase,
Webpack
andwebpack-dev-server
interact.Webpack
Andwebpack-dev-server
mainly throughExpress
middlewarewebpack-dev-middleware
to interact, this stage can be subdivided into the following steps:
webpack-dev-server
StartWebpack
packagedwatch
mode, in this modeWebpack
will monitor file changes, once a file is changed, it will re-packaged,watch
modeWebpack
packed result will not drop the disk (saved to the hard disk);webpack-dev-server
Bywebpack-dev-middleware
theWebpack
interaction,Webpack-dev-middleware
initialization receivingWebpack
theCompiler
object,Compiler
the hook can monitorWebpack
the packaging process;- If
devServer.watchContentBase=true
, thenwebpack-dev-server
change 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-server
will usesockjs
the browser andServer
between create aWebSocket
long connection, this connection is long and browserwebpack-dev-server
communication bridges, communication between them is the main content is to pass the file information (compiled modulehash
value), if this timeWebpack
monitor file modification occurred,webpack/hot/dev-server
to achieveHMR
update or refresh the page.
- Note that as follows:
webpack-dev-server
ThecontentBase
can be understood as a static resource directory on the server folder, startserver
later, you can access specific documents to a URL method + computer file path, file with theWebpack
package out of the path are not the same;- There are two monitoring file changes, the first step in the
Webpack
monitoring of the entire module dependencies changes, changes in the re-startWebpack
compile; the third step inwebpack-dev-server
their own monitoringcontentBase
file changes, the file tells the browser to refresh the page changes, there is not refresh the pageHMR
, becausecontentBase
the content of non-Webpack
packaged dependencies. WebSocket
Need server and browser has created a corresponding connection code(new WebSocket),webpack-dev-server
in a browser bychunks
inserting inwebpack-dev-server/client
this file to createWebSocket
a communication.
- Start end of this phase, when
Webpack
after monitoring file changes, this time into the file update process monitoring, whenWebpack
after a file to monitor changes in the dependency graph:
Webpack
Will re-compile the file, this time wewebpack.config.js
add plug-insHotModuleReplacementPlugin
will generate a list of differences between two files compiled(manifest)
file[hash].hot-update.json
, thismanifest JSON
file contains the change fileUpdate
contents, that is[id].[hash].hot-update.js
.webpack-dev-server
Thewebpack-dev-middler
will passWebpack
theCompiler
hook listening packing process, and then inform thewebpack-dev-server
useWebSocket
long connection push after compilinghash
value;- In addition to sending compiled
Hash
value outside,webpack-dev-server
but also through the long connection tells the browser to the current page code isinvalid
the state, need to update the new code; - The browser to get
Hash
after, will first initiate aAjax
requestmanifest
file[hash].hot-update.json
contents of the file; manifest
After the contents of the file list to get, will tellHMR
ofRuntime
those requests changeJavaScript
file, this time willRuntime
be initiated in accordance with the inventory listJSONP
request, the two compiled a difference file[id].[hash].hot-update.js
get down into the pagehead
labelscript
in execution, finally completed a full update Process.
- Summary:
webpack-dev-server
Although it can be started directlyHMR
, the real core iswebpack-dev-middleware
.webpack-dev-server
In addition to this middleware, the main function is a static server.