Preface ๐งฉ
In the front-end interview, Webpack is also one of the focus of the interviewer. If a candidate can’t webpack, in some ways it doesn’t particularly affect the interviewer’s final interview result. But in a sense, candidates are giving interviewers less credit. So, to the same should change, or seize the time to review the study, the interviewer may be involved in a variety of questions.
So in the following article, we will sort out the basic knowledge of Webpack, and summarize and answer the frequently met questions. Let’s learn ~๐
๐จ 1. Basic knowledge learning
Let’s start with a mind map to summarize some of the basics of Webpack. See ๐ below for details
For the above content, I sorted out 5 articles on Monday. Stamp webpack basics portal
You can go to the column to learn to view, at the same time, if you want to have a systematic point of learning webpack, you can directly read the book “Webpack actual combat: entry, progression and tuning”.
This book is relatively friendly for beginners and is also a book to read on Monday. I haven’t read the other books either… I’ll fill in later.
Basic knowledge learned, so we continue to look at some of the more common interview questions summary and answers ~
๐ฒ two, often meet test summary
Again, let’s start with a mind map for some interview questions that are common in Webpack. See ๐ below for details
Now let’s answer these questions one by one.
๐ฏ 3. Build and package
1. How is front-end code built and packaged?
The running flow of Webpack is a sequential process, from start to finish:
- Initialization parameters:From the configuration file and
Shell
In the statement, Q reads and merges parameters to get the final parameter; - Start compiling:Class with the parameters obtained in the previous step
Compiler
Object, loads all configured plug-ins, executes the object’srun
Method starts compiling; - Determine the entrance:Based on the configuration
entry
Find all entry files; - Compiling module: ไปEntrance to the fileGo, call all configured
Loader
Translate the module, and then find the module that the module depends on, and then recurse this step until all the entry dependent files have been processed by this step; - Complete module compilation:After the first
4
Step usedLoader
After all modules are translated, the final content of each module is obtained and the dependencies between them are obtained. - Output resources:According to the entry and module betweendependencies, assembled into a series of modules
Chunk
And then put eachChunk
Convert to a separate file and add it to the output list. This step is the last chance to modify the output. - Output complete: After determining the output content, determine the output path and file name according to the configuration, and write the file content to the file system.
In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening for the event of interest, and the plug-in can call the API provided by Webpack to change the results of The Webpack run.
In a nutshell:
- Initialization parameters:Start build, read and merge configuration parameters, load
Plugin
To instantiateCompiler
๏ผ - Compiling module: ไป
Entry
Go for eachModule
Serial calls corresponding toLoader
Translate the contents of the document and find theModule
Rely on theModule
, recursively for compilation processing; - Finished output:Will be compiled
Module
Combined intoChunk
That will beChunk
Convert to a file and output to the file system.
2. Why is the front end packaged and built?
At the code level:
- Smaller project bodies after building and packaging (
Tree-Shaking
, compress code, merge code, load faster); - High-level languages or syntax can be compiled (
TS
.ES6+
, modular,scss
); - Check code for compatibility and errors (
polyfill
ใpostcss
ใeslint
).
From the perspective of r&d:
- Make the research and development has a more unified and efficient development environment;
- Let the project team have a unified construction process and output standards;
- Integrate the company’s build specifications slowly through the roll-out and roll-out processes.
3. Webpack principle
- The entry file needs to be parsed first
entry
, the use of@babel/parser
And convert it toAST(Abstract Syntax Tree)
๏ผ - use
@babel/traverse
Plugins, go find all the files in the gatewayRely on the module
๏ผ - Then use the
@babel/core+
ๅ@babel/preset-env
Plugins that will import filesAST
toCode
๏ผ - will
2
The dependency module found in the entry file, proceedThe recursive traversal
, repeat execution1๏ผ2๏ผ3
๏ผ - rewrite
require
Delta function and delta4
Generated in theRecursive diagram
Together, output tobundle
In the.
๐ฐ 4. Module related
1. What are the differences between module Chunk bundle and Module Chunk bundle?
- The module – on behalf ofIndividual source files.
webpack
In all modules; - Chunk – Indicates the combination of multiple modules, for example
entry
ใimport()
ใsplitChunk
๏ผ - Bundle – Represents the final output file.
2. What is source Map? How are development and production environments used?
Source Map is the process of mapping compiled, packaged, and compressed code back to source code. The packaged and compressed code is not very readable, and soucre Map is needed to debug the source code. Map files will not be loaded by the browser unless developer tools are opened. The following are the most applicable approaches in both development and production environments.
Development environment: cheap-module-eval-source-map
Production environment: cheap-module-source-map
Note: Avoid inline- and eval- in production, as they increase the bundle size and reduce overall performance.
3, how to reference a self-written library lib (third-party module)
-
Filename, Library, and libraryTarget are configured in output to reference third-party libraries written by myself.
-
Resolve library reference conflicts: externals.
๐งถ 5. Loader and Plugin
What are common Loaders in Webpack
- File-loader: used frequentlyWork with images and fonts, designed to output files to a folder and then pass relative in code
url
To reference the output file. - Url-loader: this parameter is often usedWork with images and fonts, and
file-loader
Similar. The difference is, forurl-loader
For example, the user can set oneThe threshold valueWhen the value is greater than the thresholdfile-loader
Process and return the file if the value is less than the thresholdbase64
Formal coding. - Css-loader: used for loading
CSS
Files, supportmodular,The compression,File to importFeatures. - Style-loader: used to load
CSS
Code injection intoJavaScript
throughDOM
Operation loadCSS
ใ - Sass-loader: used to load
SCSS/SASS
Code conversion toCSS
The code. - Postcss-loader: extended to resolve compatibility issues
CSS
Syntax, using the next generationCSS
, can cooperate withautoprefixer
Plug-in auto-completeCSS3
The vendor prefix of.
2. What are the common plugins in WebPaack
-
Html-webpack-plugin: Automatically creates a new HTML file and automatically introduces the js file generated by packaging into this HTML file.
-
Clean-webpack-plugin: Clears the specified directory or folder.
-
Ignore-plugin: ignores some files.
-
SplitChunkPlugin: Splits the code of JS files.
-
Mini-css-extract-plugin: Split the CSS file code, for the split code, support on-demand loading.
-
Optimize – CSS-assets-webpack-plugin: used to compress CSS files and reduce the size of CSS files.
3. What is the difference between loader and plugin?
loader
, so to speak, oneModular converterFor handling the module we reference. Let’s say we want to introduce ajs
File, orcss
Format files are requiredloader
To help us deal with it.plugin
, so to speak, is an extension plug-in, which is used in theAt some point in the packing processEffect. Common arehtmlWebpackPlugin
ใcleanWebpackPlugin
And so on.
4. Have Loader been written? How to write loader?
-
It is essentially a function, in which this will be provided as a context for WebPack to populate, so we cannot set loader to an arrow function;
-
The function takes an argument that is the source of the file that webPack passes to the Loader.
-
Function this is the object provided by WebPack, which can obtain various information required by the current loader;
-
The function has asynchronous or synchronous operations, which are returned by this.callback as a string or Buffer.
The code looks like this:
// Export a function, source is the file source content that webpack passes to loader
module.exports = function(source) {
const content = doSomeThing2JsString(source);
// If the loader is configured with an options object, this.query will point to options
const options = this.query;
// Can be used as a context to parse other module paths
console.log('this.context');
/ * * this. The callback parameter: * error: error | null, when loader error to throw an error * content: String | Buffer, after loader compiled need to export the * sourceMap: the content of the generated for the convenience of debugging the compiled contents of the source map * ast: The AST static syntax tree generated by this compilation can be used directly by subsequent loaders, thus saving the process of repeatedly generating AST */
this.callback(null, content); / / asynchronous
return content; / / synchronize
}
Copy the code
5. Have you written Plugin? Describe briefly the idea of writing a plugin?
(1) Because WebPack is based on the publish and subscribe mode, many events will be broadcast during the life cycle of the running. By listening to these events, plug-ins can perform their own plug-in tasks at specific stages.
(2) Webpack compilation creates two core objects:
-
Compiler: Contains all configuration information for the WebPack environment, including options, loader, plugin, and webPack lifecycle related hooks.
-
Compilation: Parameter to the plugin’s built-in event callback function, containing the current module resources, compile-generated resources, changed files, and state information about the dependencies being tracked. When a file change is detected, a new Compilation is created.
(3) If you want to implement plugin, you also need to follow certain specifications:
-
The plug-in must either be a function or an object containing the Apply method in order to access the Compiler instance.
-
The Compiler and Compilation objects passed to each plug-in are the same reference and therefore not recommended.
-
Asynchronous events need to call the callback function when the plug-in finishes processing the task, and then tell Webpack to move on to the next flow, otherwise it will get stuck.
(4) The template for plugin implementation is as follows:
class MyPlugin {
// Webpack calls the apply method of the MyPlugin instance to pass the Compiler object to the plug-in instance
apply (compiler) {
// Find the appropriate event hooks to implement your own plugin functionality
compiler.hooks.emit.tap('MyPlugin'.compilation= > {
// compilation: Context of the current packaging build process
console.log(compilation);
// do something...}}})Copy the code
๐ฅ 6. Babel
1. Differences between Babel and Webpack
babel
Compile,JS
New syntax is a tool that it doesn’t care aboutmodular;- while
webpack
, it is aPackage build tools, it is moreloader
ๅplugin
Is concerned with modularity.
Babel-polyfill and Babel-Runtime
babel-polyfill
“Is designed to address incompatibility with older browsersES6
The new syntax variable is part of the problem, but it has one drawbackContaminate the whole situation, i.e.,@babel/preset-env
willPromise
Translate into global variablesvar _Promise
ใ- while
babel-runtime
ๅIt won’t contaminate the whole situation.babel-runtime
A separate package is provided to provide utility functions for compiling modules. To enable the pluginbabel-plugin-transform-runtime
Later,Babel
Will usebabel-runtime
Below the utility function. - Also, it is worth noting when referencing a third-party library written by yourself
lib
When, want to usebabel-runtime
ใ
3. Why can’t the Proxy be polyfilled?
-
Proxy can’t be polyfilled, which means that some of the new syntax variables are not compatible with older browsers, which is why vue3 is not compatible with older browsers.
-
Classes can be simulated with function and promises can be simulated with callback, but Proxy functions cannot be simulated with Object.defineProperty, so vue3 cannot be reduced to older browsers for now.
๐ฅ 7. Performance optimization
1. How does Webpack implement lazy loading?
-
Import () syntax.
-
Asynchronously loading files using preloading and prefetching.
-
The difference between preload and prefetch is that preload is loaded at the same time as the main file, rather than after the main file is loaded. In general, we use Prefetch and load the rest of the files we want only after the main file has finished the work. This logic and optimization of the page is perfect.
2, Webpack common performance optimization (how to optimize the webpack build speed?)
(1) From the perspective of the development environment
Production environment optimization:
- To optimize the
babel-loader
๏ผ - use
IgnorePlugin
, exclude some unused modules, and useShrink the packaging scope; - NoParse;
- HappyPack (not maintained);
- ParallelUglifyPlugin.
Development environment optimization:
- Automatic refresh: use
webpackDevServer
To implement theAutomatically refresh compilation results. - Hot module update HMR: Hot update, also known as hot replacement, is a mechanism to replace the old module with the new module without refreshing the browser.
- Use DllPlugin:
DllPlugin
Carry out subcontracting, useDllReferencePlugin
(Index link) Rightmanifest.json
Reference, let some basic will not change the code first packaged into static resources, to avoid repeated compilation waste time.
(2) From the perspective of output code
- Lazy loading;
- Extract common code;
- use
cdn
To speed up; IgnorePlugin
;- use
production
๏ผ - use
url-loader
For small imagesbase64
Coding; - Of the generated
bundle
File to addhash
Value; - The Scope of Hosting:
- The code you build will have a large number of closures, which will increase in size, create more scoped functions when you run the code, and increase memory overhead.
Scope hoisting
Put the code for all modules in one reference orderFunction scope, then rename some variables as appropriatePrevent variable name conflicts.- At the same time, it has to be
ES6
Syntax, because there are many third party libraries still useCommonJS
Syntax. - Therefore, in order to give full play to
Scope hoisting
The role of the need to configuremainFields
Third-party modules are preferredjsnext:main
The point toES6
Modular syntax.
๐ฌ 8. Conclusion
In the above article, we summarized some common questions about Webpack from five aspects: build and package, module related, Loader and Plugin, Babel, and performance optimization. I believe that through the above study, we have a certain understanding of the content of this piece. So that’s the end of webpack! Hope to help you ~
If this article is wrong or you have something to add, please leave a comment or contact VX :MondayLaboratory.
Finally, I wish everyone who read this article can get their favorite offer ~๐ฅ๐ฅ๐ฅ
๐ฃ Egg One More Thing
(: References
๐ a dozen more Webpack interview questions
๐ Tencent interviewer: brother, you say you will Webpack, that say his principle?
๐ interviewer: Tell me the difference between Loader and Plugin in Webpack. How to write Loader, Plugin?
(: PDF available
๐ wechat public account Monday laboratory, click the navigation bar below the interview column briefly view the keyword to obtain ~
(: Update address
๐ offer comes to the interview column
) Introduction
- Pay attention to the public number Monday laboratory, the first time to pay attention to quality articles, more selected columns for you to unlock ~
- If this article is useful to you, be sure to leave a footprint
- That’s all for this article! See you next time! ๐ ๐ ๐