Webpack interview questions

Time:2021-10-18

From the density of hair and able walking posture, I noticed that the interviewer sitting in front of me was also a good hand. As usual, I’m going to spend three minutes introducing myself. During this period, my eyes were attracted by the 16 inch MacBook Pro. I made full preparations for this self introduction and was confident to conquer the interviewer. As I expected, the interviewer was introduced into my field.

It seems that you are familiar with webpack. Let me test you

1. What are the common loaders? What loaders have you used?

(I began to quote the dish name familiar)

  • raw-loader: load the original contents of the file (UTF-8)
  • file-loader: output the file to a folder, and reference the output file (processing pictures and fonts) through the relative URL in the code
  • url-loader: similar to file loader, the difference is that the user can set a threshold, return its publicpath when the threshold is greater than, and return the file Base64 format encoding (processing pictures and fonts) when the threshold is less than
  • source-map-loader: load additional source map files to facilitate breakpoint debugging
  • svg-inline-loader: inject the compressed SVG content into the code
  • image-loader: load and compress picture files
  • json-loaderLoad JSON file (included by default)
  • handlebars-loader: compile the handlebars template into a function and return
  • babel-loader: convert ES6 to Es5
  • ts-loader: convert typescript to JavaScript
  • awesome-typescript-loader: convert typescript to JavaScript, with better performance than TS loader
  • sass-loader: convert SCSS / sass code to CSS
  • css-loader: load CSS, support modularization, compression, file import and other features
  • style-loader: inject CSS code into JavaScript and load CSS through DOM operation
  • postcss-loader: extend CSS syntax, use next generation CSS, and automatically supplement CSS3 prefix with autoprefixer plug-in
  • eslint-loader: check JavaScript code through eslint
  • tslint-loader: check typescript code through tslint
  • mocha-loader: code to load Mocha test cases
  • coverjs-loader: calculate the coverage of the test
  • vue-loader: load vue.js single file component
  • i18n-loader: Internationalization
  • cache-loader: it can be added before some loaders with high performance overhead to cache the results to disk

For more loaders, please refer to the official website

(Interviewer: very good. I know a lot)

2. What are the common plugins? What plugins have you used?

(the big brother seems to be addicted. Continue to start the routine operation)

  • define-plugin: define environment variables (specify mode after webpack 4 and it will be automatically configured)
  • ignore-plugin: ignore some files
  • html-webpack-plugin: simplify HTML file creation (dependent on HTML loader)
  • web-webpack-plugin: it can easily output HTML for single page applications, which is easier to use than HTML webpack plugin
  • uglifyjs-webpack-plugin: ES6 compression is not supported (before webpack4)
  • terser-webpack-plugin: support compression ES6 (webpack4)
  • webpack-parallel-uglify-plugin: multi process code compression to improve construction speed
  • mini-css-extract-plugin: separate style files, extract CSS as a separate file, and support on-demand loading (instead of extract text webpack plugin)
  • serviceworker-webpack-plugin: add offline caching function for web applications
  • clean-webpack-plugin: Directory cleanup
  • ModuleConcatenationPlugin: turn on scope hosting
  • speed-measure-webpack-plugin: you can see the execution time of each loader and plugin (the whole packaging time, each plugin and loader time)
  • webpack-bundle-analyzer: visualize the volume of the webpack output file (business components, dependent third-party modules)

For more plugins, please refer to the official website

(Double Kill)

3. What’s the difference between loader and plugin?

(I knew you would ask this. I covered my smile with my hand)

LoaderIn essence, it is a function that converts the received content and returns the converted result. Because webpack only knows JavaScript, loader becomes a translator and preprocesses the translation of other types of resources.

PluginIs a plug-in, based on the event flow frameworkTapable, the plug-in can extend the function of webpack. Many events will be broadcast during the life cycle of webpack. Plugin can listen to these events and change the output results through the API provided by webpack at an appropriate time.

LoaderIt is configured in module.rules as the parsing rule of the module. The type is array. Each item is an object, which contains attributes such as test (type file), loader, options (parameters), etc.

PluginIt is configured separately in plugins. The type is array. Each item is an instance of plugin, and the parameters are passed in through the constructor.

4. Webpack construction process briefly

The running process of webpack is a serial process. The following processes will be executed from start to end:

  • Initialization parameters: read and merge parameters from configuration files and shell statements to get the final parameters
  • Start compilation: initialize the compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the run method of the object to start compiling
  • Determine the entrance: find all the entry files according to the entry in the configuration
  • Compilation module: starting from the entry file, call all configured loaders to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have been processed in this step
  • Complete module compilation: after using loader to translate all modules in step 4, the final translated content of each module and their dependencies are obtained
  • Output resources: assemble chunks containing multiple modules according to the dependencies between entries and modules, and then convert each chunk into a separate file to be added to the output list. This step is the last chance to modify the output content
  • 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,WebpackA specific event will be broadcast at a specific time point. After listening to the event of interest, the plug-in will execute specific logic, and the plug-in can call the API provided by webpack to change the running result of webpack.

in brief

  • Initialization: start the build, read and merge the configuration parameters, load the plugin, and instantiate the compiler
  • Compilation: starting from the entry, call the corresponding loader for each module to translate the contents of the file, find the module that the module depends on, and compile recursively
  • Output: combine the compiled module into a chunk, convert the chunk into a file, and output it to the file system

5. What plug-ins have you used to improve efficiency when developing with webpack?

(this question is quite practical, and the user experience should be started from an early age)

  • webpack-dashboard: it can display relevant packaging information more friendly.
  • webpack-merge: extract common configuration to reduce duplicate configuration codes
  • speed-measure-webpack-plugin: SMP for short. Analyzing the time-consuming of loader and plugin in the webpack packaging process helps to find the performance bottleneck in the construction process.
  • size-plugin: monitor resource volume changes and find problems as soon as possible
  • HotModuleReplacementPlugin: module hot replacement

6. What is a source map? How to use the production environment?

source mapIt is the process of mapping compiled, packaged and compressed code back to source code. The packed and compressed code does not have good readability. If you want to debug the source code, you need soucre map.

As long as the map file does not open the developer tool, the browser will not load it.

There are generally three processing schemes for online environment:

  • hidden-source-mapSentry uses a third-party error monitoring platform:
  • nosources-source-map: only the specific number of lines and the error stack of the source code will be displayed. Higher security than sourcemap
  • sourcemap: open the. Map file only to the white list through nginx settings (intranet)

Note: avoid use in productioninline-andeval-, because they increase the size of the bundle and reduce the overall performance.

7. Do you know the principle of module packaging?

Webpack actually creates an environment for each module to export and import. In essence, it does not modify the code execution logic, and the code execution order is completely consistent with the module loading order.

8. What is the principle of file monitoring?

When the source code changes, a new output file is automatically rebuilt.

Webpack enables listening mode in two ways:

  • When starting the webpack command, bring the — watch parameter
  • Set watch: true in the configuration webpack.config.js

Disadvantages: you need to refresh the browser manually every time

Principle: poll to determine whether the last editing time of a file has changed. If a file has changed, it will not immediately tell the listener, but cache it first, etcaggregateTimeoutThen execute.

module.export = {    
    //The default is false, that is, it is not enabled
    watch: true,
    //Watchoptions is meaningful only when listening mode is enabled
    watchOptions: {
        //It is empty by default. It does not listen to files or folders. Regular matching is supported
        ignored: /node_modules/,
        //After listening to the change, it will wait 300ms for execution. The default is 300ms
        aggregateTimeout:300,
        //Judge whether the file has changed by constantly asking the system whether the specified file has changed. By default, ask 1000 times per second. Poll: 1000
    }
}

9. Let’s talk about the hot update principle of webpack

(knock on the blackboard, this question must be tested)

WebpackHot update is also called hot replacement(Hot Module Replacement), abbreviated asHMR。 This mechanism can replace the old module with the new module without refreshing the browser.

The core of HMR is that the client pulls the updated files from the server. To be exact, it is the chunk diff (the part of the chunk that needs to be updated). In fact, a link is maintained between WDS and the browserWebsocket, when the local resource changes, WDS will push the update to the browser and bring the hash during construction to compare the client with the last resource. After comparing the differences, the client will send a message to WDSAjaxRequest to get the changed content (file list, hash), so that the client can continue to initiate to WDS with the help of this informationjsonpRequest an incremental update of the chunk.

The subsequent parts (how to deal with the incremental update? Which states should be retained? Which need to be updated?)HotModulePluginIt provides relevant APIs for developers to process their own scenarios, such asreact-hot-loaderandvue-loaderThese APIs are used to implement HMR.

(Interviewer: good, the young man has good expression ability)

(basic operation, do not 6)

10. How to monitor and analyze the bundle volume?

VSCodeThere is a plug-in inImport CostIt can help us monitor the size of the introduced module in real time, and can also usewebpack-bundle-analyzergeneratebundleModule composition diagram showing the occupied volume.

bundlesizeThe toolkit enables automated resource volume monitoring.

11. What is the document fingerprint? How to use it?

The file fingerprint is the suffix of the file name output after packaging.

  • Hash: it is related to the construction of the whole project. As long as the project file is modified, the hash value of the whole project construction will change
  • Chunkhash: it is related to the chunk packaged by webpack. Different entries will produce different chunkcash
  • Contenthash: the hash is defined according to the file content. If the file content remains unchanged, the contenthash remains unchanged

JS file fingerprint setting

Set the filename of output and use chunkash.

module.exports = {
    entry: {
        app: './scr/app.js',
        search: './src/search.js'
    },
    output: {
        filename: '[name][chunkhash:8].js',
        path:__dirname + '/dist'
    }
}

CSS file fingerprint settings

Set the filename of minicssextractplugin and use contenthash.

module.exports = {
    entry: { 
        app: './scr/app.js',
        search: './src/search.js'
    }, 
    output: {
        filename: '[name][chunkhash:8].js',
        path:__dirname + '/dist'
    },
    plugins:[
        new MiniCssExtractPlugin({
            filename: `[name][contenthash:8].css`
        })
    ]
}

File fingerprint settings for pictures

Set the name of file loader and use hash.

Placeholder name and meaning

  • ext     Resource suffix
  • name     File name
  • path     Relative path to file
  • folder   Folder where the file is located
  • contenthash   The content of the file is hash, which is generated by MD5 by default
  • hash         The hash of file content is generated by MD5 by default
  • emoji         A random emoj that refers to the contents of the file
const path = require('path');
module.exports = { 
    entry: './src/index.js',
    output: {
        filename:'bundle.js',
        path:path.resolve(__dirname, 'dist') 
    }, 
    module:{
        rules:[{
            test:/\.(png|svg|jpg|gif)$/,
            use:[{
                loader:'file-loader',
                options:{
                    name:'img/[name][hash:8].[ext]'
                }  
            }] 
        }]
    }
}

12. In practical projects, hundreds of lines of configuration files are common. How to ensure that each loader works as expected?

have access toenforceEnforcementloaderThe order of action,preOn behalf of all normal loaders,postIs executed after all loaders. (not recommended by inline officials)

13. How to optimize the construction speed of webpack?

(the question is like can you say it“From URL input to page display what happened”Same)

I just want to say: how long do you want me to talk

(Interviewer:..)

  • useHigh versionWebpack and node.js
  • Multi process / multi instance construction: happypack (no maintenance), thread loader
  • Compressed code

    • webpack-paralle-uglify-plugin
    • Uglifyjs webpack plugin enable parallel parameter (ES6 is not supported)
    • Terser webpack plugin enable parallel parameter
    • Multi process parallel compression
    • Extract the CSS code in chunk to a separate file through mini CSS extract plugin, and enable cssnano to compress CSS through the minimize option of CSS loader.
  • Picture compression

    • Use imagemin based on node Library (many customization options and can handle multiple image formats)
    • Configure image webpack loader
  • Narrow packaging scope

    • Exclude / include (determine the range of loader rules)
    • Resolve.modules indicates the absolute path of the third-party module (reducing unnecessary lookups)
    • Resolve.mainfields only uses the main field as the entry file description field (reduce the search steps and consider the entry file description fields of all third-party modules that the runtime depends on)
    • Resolve.extensions minimize the possibility of suffix attempts
    • Noparse ignores the libraries that do not need to be parsed at all (they will not be parsed but will still be packaged in the bundle. Note that the ignored files should not contain modular statements such as import, require, define, etc.)
    • Ignoreplugin (completely exclude module)
    • Rational use of alias
  • Extract page public resources

    • Use HTML webpack externals plugin to import the basic package through CDN and not into the bundle
    • Splitchunkplugin is used to separate (public script, basic package and page public file) (built-in in webpack 4), replacing the Commons chunkplugin plug-in
    • Base package separation:
  • DLL

    • Use dllreferenceplugin to subcontract and dllreferenceplugin (index link) to reference manifest.json, so that some code that will not be changed is packaged into static resources first to avoid repeated compilation and waste of time.
    • Hashedmodulidsplugin can solve the problem of module digital ID
  • Make full use of cache to improve secondary construction speed

    • Babel loader enable cache
    • Terser webpack plugin enable caching
    • Use cache loader or hard source webpack plugin
  • Tree shaking

    • Purgecss webpack plugin and mini CSS extract plugin (recommended)
    • During the packaging process, modules not referenced in the project are detected and marked, and they are removed from the final bundle during resource compression (only effective for ES6 modlue). ES6 module modules are used as much as possible in development to improve the efficiency of tree shaping
    • Disable the module dependency resolution of Babel loader, otherwise all modules received by webpack are converted modules in the form of commonjs, and tree shaking cannot be performed
    • Use purify CSS (not maintained) or uncss to remove useless CSS code
  • Scope hoisting

    • There will be a large number of closures in the built code, resulting in an increase in volume, more function scopes created when running the code, and greater memory overhead. Scope hoisting places the codes of all modules in a function scope according to the reference order, and then renames some variables appropriately to prevent variable name conflicts
    • It must be ES6 syntax, because many third-party libraries still use commonjs syntax. In order to give full play to the role of scope hosting, mainfields needs to be configured to give priority to the ES6 modular syntax pointed to in jsnext: main for third-party modules
  • Dynamic Polyfill

    • It is recommended to use Polyfill service to only return the required Polyfill to users for community maintenance. (some domestic exotic browsers UA may not be recognized, but can be downgraded to return all required Polyfill)

For more optimization, please refer to the official website – build performance

14. You just mentioned code segmentation. What is the essence of code segmentation? What’s the point?

The essence of code segmentation isSource code directly onlineandPackage into a unique script main.bundle.jsOne of the two extreme schemes is more suitable for the intermediate state of the actual scene.

Akali: take down the glory sword and seek balance in chaos

“Exchange acceptable server performance pressure for a better user experience.”

The source code goes online directly: Although the process is controllable, there are many HTTP requests and high performance overhead.

Packaged into a unique script: it’s cool to finish the shuttle, the server pressure is small, but the page blank period is long, and the user experience is not good.

(Easy peezy right)

15. Have you written about loader? Briefly describe the idea of writing loader?

The loader supports chain calling, so the development needs to strictly follow the “single responsibility”, and each loader is only responsible for what it needs to be responsible for.

The loader API can be found on the official website

  • The loader runs in node.js. We can call the API of any node.js or install a third-party module to call it
  • The original contents passed from the webpack to the loader are strings encoded in UTF-8 format. In some scenarios, when the loader processes binary files, you need to tell the webpack whether the loader needs binary data through exports.raw = true
  • Asynchronize the loader as much as possible. If the amount of calculation is very small, synchronization can also be used
  • The loader is stateless and we should not keep the state in the loader
  • Use the utilities provided by loader utils and schema utils
  • Load local loader method

    • Npm link
    • ResolveLoader

16. Have you written plugin? Briefly describe the idea of writing plugin?

Webpack will broadcast many events in the running life cycle. Plugin can listen to these events and hook in the custom functions you want to add at a specific stage. The tapable event flow mechanism of webpack ensures the order of plug-ins and makes the whole system extensible.

Plugin’s API can be found on the official website

  • Compiler exposes hooks associated with the entire lifecycle of the webpack
  • Compilation exposes smaller granularity event hooks related to modules and dependencies
  • The plug-in needs to bind the apply method on its prototype to access the compiler instance
  • The compiler and compilation objects passed to each plug-in are the same reference. If their properties are modified in a plug-in, subsequent plug-ins will be affected
  • Find the appropriate event point to complete the desired function

    • When the emit event occurs, you can read and modify the final output resources, code blocks, modules and their dependencies (the emit event is the last time to modify the webpack output resources)
    • Watch run is triggered when the dependent file changes
  • Asynchronous events need to call the callback function when the plug-in finishes processing the task to inform webpack to enter the next process, otherwise it will get stuck

17. Talk about Babel principle

Most JavaScript parsers followestreeSpecification, Babel was originally based onacornThe Babel project (lightweight modern JavaScript parser) is roughly divided into three parts:

  • Parsing: converting code to AST

    • Lexical analysis (word segmentation): the code (string) is divided into token streams, that is, an array of syntax units
    • Syntax analysis: analyze the token stream (the array generated above) and generate ast
  • Conversion: access the ast node for conversion operation to produce a new ast

    • Taro is a small program syntax conversion completed by Babel
  • Generate: generate code based on the new ast

Students who want to know how to implement a compiler step by step can move to the open source project the super tiny compiler once recommended by Babel’s official website

Interviewer: (I’m thirsty. Let’s have a rest and have the second half later)

The interviewer picked up the cool Longjing next to him and took a drink.

(the young man has something)

reference resources

  • Webpack in simple terms
  • Webpack actual combat
  • Play webpack

Recommended Today

Webpack build Vue project

Precautions for webpack building Vue project Download Plugin and loader Write configuration item Write component Introduction component Import dependency directory structure |–>config|—–>webpack.base.js|—–>webpack.dev.js|—–>webpack.pro.js|–>src|—–>HTML (htmlwebpackplugin rendered here)|———>index.html|—–>router|———>index.js|—–>views|———>Home.vue|———>Login.vue|—–>App.vue|—–>main.js|–>node_modules|–>package.jsonDependent package all:package.json { “scripts”: { “dev”: “webpack-dev-server –config config/webpack.dev.js” }, “devDependencies”: { “HTML webpack plugin”: “^ 4.2.0”, // mixed with HTML “vue”: “^2.6.11”, “vue-loader”: “^15.9.1”, “vue-router”: “^3.1.6”, “vue-template-compiler”: “^2.6.11”, “webpack”: […]