A brief introduction to the working principle of webpack

1. The principle of webpack

1. Core concepts

(1) entry: The entry of an executable module or library.

(2) chunk: Multiple files form a code block. The executable module and the modules it depends on can be combined into a chunk, which is packaging.

(3) loader: file converter. For example, convert es6 to es5, scss to css, etc.

(4) plugin: A plugin that extends webpack functionality. Add extension hooks to the life cycle nodes built by webpack to add functions.

2. Webpack construction process (principle)

A series of processes from starting the build to outputting the results:

(1) Initialization parameters: parse the webpack configuration parameters, merge the parameters passed in by the shell and configured in the webpack.config.js file, and form the final configuration result.

(2) Start compiling: Initialize the compiler object with the parameters obtained in the previous step, register all configured plug-ins, and the plug-ins listen to the event nodes of the webpack construction life cycle, respond accordingly, and execute the run method of the object to start compiling.

(3) Determine the entry: from the entry entry of the configuration, start to parse the file to build the AST syntax tree, find out the dependencies, and recurse down.

(4) Compile the module: In recursion, according to the file type and loader configuration, call all configured loaders to convert the file, then find out the modules that the module depends on, and then recurse this step until all the files that the entry depends on have passed this step deal with.

(5) Complete module compilation and output: After recursion, get the results of each file, including each module and their dependencies, and generate a code block chunk according to the entry configuration.

(6) Output completed: output all chunks to the file system.

Note: There are a series of plug-ins doing the right thing at the right time during the build life cycle. For example, UglifyPlugin will use UglifyJs compression to overwrite the result before the loader transforms recursively.

Summarize

In fact, webpack is relatively simple, and the essence can be summed up in one sentence:

webpack是一个打包模块化js的工具,可以通过loader转换文件,通过plugin扩展功能。

If webpack makes you feel complicated, it must be because of various loaders and plugins.

Guess you like

Origin blog.csdn.net/weixin_48494427/article/details/127226471