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 andShellIn the statement, Q reads and merges parameters to get the final parameter;
  • Start compiling:Class with the parameters obtained in the previous stepCompilerObject, loads all configured plug-ins, executes the object’srunMethod starts compiling;
  • Determine the entrance:Based on the configurationentryFind all entry files;
  • Compiling module: ไปŽEntrance to the fileGo, call all configuredLoaderTranslate 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 first4Step usedLoaderAfter 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 modulesChunkAnd then put eachChunkConvert 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, loadPluginTo instantiateCompiler ๏ผ›
  • Compiling module: ไปŽ EntryGo for eachModuleSerial calls corresponding toLoaderTranslate the contents of the document and find theModuleRely on theModule, recursively for compilation processing;
  • Finished output:Will be compiledModuleCombined intoChunkThat will beChunkConvert 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 firstentry, the use of@babel/parserAnd convert it toAST(Abstract Syntax Tree) ๏ผ›
  • use@babel/traversePlugins, go find all the files in the gatewayRely on the module ๏ผ›
  • Then use the@babel/core+ ๅ’Œ @babel/preset-envPlugins that will import filesASTtoCode ๏ผ›
  • will2The dependency module found in the entry file, proceedThe recursive traversal, repeat execution1๏ผŒ2๏ผŒ3 ๏ผ›
  • rewriterequireDelta function and delta4Generated in theRecursive diagramTogether, output tobundleIn the.

๐ŸŽฐ 4. Module related

1. What are the differences between module Chunk bundle and Module Chunk bundle?

  • The module – on behalf ofIndividual source files.webpackIn all modules;
  • Chunk – Indicates the combination of multiple modules, for exampleentry ใ€ 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 codeurlTo reference the output file.
  • Url-loader: this parameter is often usedWork with images and fonts, andfile-loaderSimilar. The difference is, forurl-loaderFor example, the user can set oneThe threshold valueWhen the value is greater than the thresholdfile-loaderProcess and return the file if the value is less than the thresholdbase64Formal coding.
  • Css-loader: used for loadingCSSFiles, supportmodular,The compression,File to importFeatures.
  • Style-loader: used to loadCSSCode injection intoJavaScriptthroughDOMOperation loadCSS ใ€‚
  • Sass-loader: used to loadSCSS/SASSCode conversion toCSSThe code.
  • Postcss-loader: extended to resolve compatibility issuesCSSSyntax, using the next generationCSS, can cooperate withautoprefixerPlug-in auto-completeCSS3The 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 ajsFile, orcssFormat files are requiredloaderTo 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 ใ€ cleanWebpackPluginAnd 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

  • babelCompile,JSNew syntax is a tool that it doesn’t care aboutmodular;
  • whilewebpack, it is aPackage build tools, it is moreloader ๅ’Œ pluginIs concerned with modularity.

Babel-polyfill and Babel-Runtime

  • babel-polyfill“Is designed to address incompatibility with older browsersES6The new syntax variable is part of the problem, but it has one drawbackContaminate the whole situation, i.e.,@babel/preset-envwillPromiseTranslate into global variablesvar _Promise ใ€‚
  • whilebabel-runtime ๅˆ™It won’t contaminate the whole situation.babel-runtimeA separate package is provided to provide utility functions for compiling modules. To enable the pluginbabel-plugin-transform-runtimeLater,BabelWill usebabel-runtimeBelow the utility function.
  • Also, it is worth noting when referencing a third-party library written by yourselflibWhen, 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 thebabel-loader ๏ผ›
  • useIgnorePlugin, exclude some unused modules, and useShrink the packaging scope;
  • NoParse;
  • HappyPack (not maintained);
  • ParallelUglifyPlugin.

Development environment optimization:

  • Automatic refresh: usewebpackDevServerTo 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:DllPluginCarry out subcontracting, useDllReferencePlugin(Index link) Rightmanifest.jsonReference, 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;
  • usecdnTo speed up;
  • IgnorePlugin;
  • useproduction ๏ผ›
  • useurl-loaderFor small imagesbase64Coding;
  • Of the generatedbundleFile to addhashValue;
  • 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 hoistingPut 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 beES6Syntax, because there are many third party libraries still useCommonJSSyntax.
    • Therefore, in order to give full play toScope hoistingThe role of the need to configuremainFieldsThird-party modules are preferredjsnext:mainThe point toES6Modular 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! ๐Ÿ‘‹ ๐Ÿ‘‹ ๐Ÿ‘‹