The react JSX code has to be compiled before it can be used in the browser. Code browsers such as Sass and less are also not supported. If you get rid of these frameworks, the efficiency of development drops dramatically. Among many front-end engineering tools, WebPack stands out as the most popular front-end construction tool today. However, most users are simply able to use it without knowing its underlying principles. Hope that through the following interview summary can help you review the old and learn new, check the deficiency, know why and know why.

The problem in

  1. How is Webpack different from Grunt and gulp?
  2. What other tools are similar to WebPack? Talk about why you ultimately chose (or abandoned) Webpack.
  3. What are the common loaders? What problems do they solve?
  4. What are the common plugins? What problems do they solve?
  5. What is the difference between Loader and Plugin?
  6. What is the webPack build process? The process from reading configuration to output file is as complete as possible
  7. Have you written Loader and Plugin? Describe the idea of writing a Loader or plugin?
  8. How does webpack’s hot update work? How does that work?
  9. How can YOU leverage WebPack to optimize front-end performance? (Improved performance and experience)
  10. How can I speed up webPack building?
  11. How to configure a single page application? How to configure a multi-page application?
  12. What do YOU need to pay attention to when packaging NPM? How can WebPack be used for better builds?
  13. How to implement on-demand loading in a VUE project?

Problem solving

1. How is Webpack different from Grunt and gulp?

Grunt and Gulp were popular in the early days. Webpack is relatively mainstream now, but gulp is still used for some lightweight tasks, such as packaging CSS files separately.

Grunt and gulp are based on tasks and streams (tasks, streams). Similar to jQuery, find a file (or a class of files) and do a series of chain operations on it to update the data on the stream. The chain operations constitute a single task, and multiple tasks constitute the entire Web build process.

Webpack is portal based. Webpack will automatically recursively parse all the resource files that need to be loaded by the entry, then use different loaders to process different files, and use Plugin to extend WebPack functionality.

So to sum up:

  • In terms of building ideas

Gulp and Grunt require developers to split the whole front-end construction process into multiple ‘tasks’ and properly control the call relationship of all’ tasks’. Webpack requires developers to find the entry point and figure out what Loader to use for different resources and what to parse and process

  • For knowledge background

Gulp is more like a back end developer, you need to know the whole process very well. Webpack is more like a front end developer

2. What other tools are similar to WebPack? Talk about why you ultimately chose (or abandoned) Webpack.

There are also several major port-based packaging tools:

  • webpack
  • rollup
  • parcel

In terms of application scenarios:

  • Webpack is ideal for large and complex front-end site builds
  • Rollup is suitable for packaging base libraries such as Vue and React
  • Parcel is suitable for simple experimental projects, and it allows for quick results with a low threshold

Because parcel provides limited debugging information during packaging, it is difficult to debug if a packaging error occurs. Therefore, it is not recommended to use Parcel for complex projects

3. What are common Loaders? What problems do they solve?

  • File-loader: Outputs files to a folder, referencing the output file with a relative URL in the code
  • Url-loader: similar to file-loader, but can inject the contents of files into code base64 if the files are too small
  • Source-map-loader: Loads additional source map files to facilitate breakpoint debugging
  • Image-loader: loads and compresses image files
  • Babel-loader: Convert ES6 to ES5
  • Css-loader: loads the CSS and supports features such as modularization, compression, and file import
  • Style-loader: Inserts CSS code into JavaScript and loads CSS via DOM manipulation.
  • Eslint-loader: Checks JavaScript code through ESLint

4. What are the common plugins? What problems do they solve?

  • Define-plugin: Defines environment variables
  • Commons-chunk-plugin: Extract common code
  • Uglifyjs-webpack-plugin: Compress ES6 code with UglifyES

5. The difference between Loader and Plugin?

Different functions

  • Loader is a Loader. Webpack treats all files as modules, but Webpack natively only parses JS files, and if you want to package other files, you use loader. So what Loader does is give WebPack the ability to load and parse non-javascript files.
  • A Plugin is a Plugin. Plugin can extend the functionality of WebPack to make it more flexible. A number of events are broadcast during the life cycle of a Webpack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by Webpack.

Different usage

  • Loader is configured in module.rules, which means that it exists as a parsing rule for modules. The type is array, each item is an Object, which describes the type of file (test), what to use (loader), and the parameters (options) to use.
  • Plugins are configured separately in plugins. Each item is an instance of plugin, and the parameters are passed in through the constructor.

6. What is the webpack build process? The process from reading configuration to output file is as complete as possible

The running flow of Webpack is a sequential process, from start to finish:

  1. Initialization parameters: read and merge parameters from configuration files and Shell statements to get the final parameters;
  2. Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the object’s run method to start compiling.
  3. Determine entry: find all entry files according to the entry in the configuration;
  4. Module compilation: Starting from the entry file, call all configured Loader 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 gone through this step;
  5. Complete module compilation: After using Loader to translate all modules in step 4, obtain the final content of each module after translation and the dependencies between them;
  6. Output resources: assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
  7. Output complete: After determining the output content, determine the output path and file name based on 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 running result of Webpack.

7. Have Loader and Plugin been written? Describe the idea of writing a Loader or plugin?

Loader acts as a “translator” to escape the read source file content into the new file content, and each Loader through the chain operation, the source file step by step to the desired shape.

When writing a Loader, follow a single principle. Each Loader does only one “escape” job. Each Loader retrieves the content of the source file, which can be output by returning a value, or it can call this.callback() to return the content to Webpack. You can also use this.async() to generate a callback function and use this callback to output the processed content. In addition, Webpack also provides a set of tools for developing Loaders – loader-utils.

Compared with Loader, Plugin writing is much more flexible. Webpack broadcasts a number of events during its run life, and the Plugin can listen for these events and change the output when appropriate through the API provided by WebPack.

8. How does the webpack hot update work? How does that work?

Hot updates to Webpack are also known as Hot Module Replacement, or HMR. This mechanism allows you to replace the old module with the new one without refreshing the browser.

Principle:

The first thing to know is that both the server and client side do the processing

  1. First, in Webpack’s Watch mode, a file in the file system changes, WebPack listens to the file changes, recompiles and packages the module according to the configuration file, and saves the packaged code in memory through a simple JavaScript object.
  2. The second step is the interface interaction between Webpack-dev-server and Webpack. In this step, it’s mainly the interaction between Webpack-Dev-middleware of Dev-server and Webpack. Webpack-dev-middleware calls the API exposed by Webpack to monitor code changes and tells Webpack to pack the code into memory.
  3. The third step is a monitoring of file changes by Webpack-dev-server, which is different from the first step in that it does not monitor code changes for repackaging. . When we are in the configuration file is configured with devServer watchContentBase to true, the Server will listen to these configuration static files in the folder change, change will notify the browser after the live for the application to reload. Notice that this is browser refresh, and HMR are two different things.
  4. The fourth step is also the work of the webpack-dev-server code. This step mainly uses sockJS (webpack-dev-server dependency) to establish a websocket long connection between the browser and the server. This tells the browser about the status of the various stages of the Webpack compilation and packaging, as well as the information that the Server listens for static file changes in step 3. The browser performs different operations based on these socket messages. Of course, the most important information passed by the server is the hash value of the new module, and the subsequent steps use this hash value to perform module hot replacement.
  5. The webpack-dev-server/client cannot request updated code and does not perform hot module operations, handing the work back to Webpack. The job of webpack/hot/dev-server is to decide whether to refresh the browser or hot update the module based on the information passed to it by webpack-dev-server/client and the configuration of dev-server. Of course, if you just refresh the browser, there are no further steps.
  6. HotModuleReplacement runtime is the centre of the client HMR, step on it receives hash value passed to his new module, it through JsonpMainTemplate. Runtime sends an Ajax request to the server end, The server returns a JSON that contains the hash values of all the modules to be updated. Once the updated list is retrieved, the module requests the latest module code again via JSONP. These are steps 7, 8 and 9 in the figure above.
  7. In step 10, the HotModulePlugin will compare the old and new modules and decide whether to update the module. After the decision is made, the dependency relationship between the modules will be checked and the dependency references between the modules will be updated.
  8. As a final step, when HMR fails, we fall back to live Reload, which is a browser refresh to get the latest packaging code.

9. How can WEBpack be used to optimize front-end performance? (Improved performance and experience)

Optimizing front-end performance with WebPack means optimizing the output of WebPack so that the packaged end result runs quickly and efficiently in the browser.

  • Compress the code. Remove unnecessary code, comments, simplify code writing, and so on. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize to compress CSS
  • CDN acceleration. During the build process, the referenced static resource path is changed to the corresponding path on the CDN. The resource path can be modified using the Webpack for the output parameter and the publicPath parameter of each loader
  • Removing dead code (Tree Shaking) Remove pieces of code that never go anywhere. This can be done by appending the parameter optimize-minimize when starting the Webpack
  • Extract common code.

10. How to speed up webPack construction?

  1. In multi-entry cases, the CommonsChunkPlugin is used to extract common code
  2. Use the externals configuration to extract common libraries
  3. The precompiled resource module uses the DllPlugin to precompile NPM packages that we reference but never modify, and then loads the precompiled modules in via the DllReferencePlugin.
  4. Use Happypack to achieve multi-threaded accelerated compilation
  5. Use Webpack-Uglify-Parallel to increase the compression speed of uglifyPlugin. In principle, Webpack-Ugli-fi – Parallel uses multi-core parallel compression to improve compression speed
  6. Use tree-shaking and Scope compensation to weed out redundant code

11. How to configure a single page app? How to configure a multi-page application?

Single-page application can be understood as the standard mode of Webpack, and can be directly referred to the entry of order page application in Entry, which will not be described here

For multi-page applications, webPack’s AutoWebPlugin can be used for simple, automated builds, but only if the project’s directory structure complies with its preset specifications. Note the following in multi-page applications:

  • Each page has common code that can be pulled out to avoid repeated loading. For example, every page references the same set of CSS stylesheets
  • As your business grows, pages can be added, so it’s important to make the entry configuration flexible enough to avoid having to change the build configuration every time you add a new page

12. What should BE paid attention to when packaging NPM? How can WebPack be used for better builds?

Npm is currently the largest repository of JavaScript modules, with reusable modules uploaded from developers around the world. You may only be a user of JS modules, but in some cases you will choose to upload your own modules. NPM module upload method can go to the official website for learning, here only explains how to use Webpack to build.

Note the following issues for the NPM module:

  1. To support the CommonJS modularity specification, require that the packaged final result also comply with this rule.
  2. The Npm module consumer’s environment is uncertain and most likely does not support ES6, so the final result of the package should be written in ES5. And if ES5 is converted, you’d better upload it with SourceMap.
  3. Npm package size should be as small as possible (some repositories limit package size)
  4. Distributed modules should not be packaged with dependent modules, and users should be given the option to install them themselves. This prevents the underlying module from being repackaged by the module user.
  5. Modules of UI component classes should also include other resource files that depend on them, such as.css files.

Based on the above considerations, we can make the following extensions and optimizations to the WebPack configuration:

  1. Set output.libraryTarget=’commonjs2′ to make output code conform to the CommonjS2 modularity specification for other modules to import
  2. A solution to output ES5 code: Use babel-Loader to convert ES6 code into ES5 code. Publish debugging by turning on devtool: ‘source-map’ to print SourceMap.
  3. Solution to Npm package size minimization: Babel injects helper functions when converting ES6 code to ES5 code, resulting in the code for this helper function being included in every output file, resulting in code redundancy. The solution is to modify the. Babelrc file and add transform-Runtime to it
  4. Solution to not packaging dependent modules into NPM modules: Use the externals configuration item to tell WebPack which modules do not need to be packaged.
  5. For the dependent resource file packaging solution: through csS-loader and extract-text-webpack-plugin, configuration is as follows:

13. How to implement load on demand in VUE project?

Off-the-shelf UI component libraries such as ElementUI, iView, etc., are often introduced in order to quickly develop front-end projects, but their size, as well as the functionality they provide, can be enormous. Normally, we only need a few components, but we pack a huge library of components into our source code, causing unnecessary overhead.

However, many component libraries already provide ready-made solutions, such as Element’s babel-plugin-Component and AntDesign’s babel-plugin-import. Set this parameter in the. Babelrc configuration or in the babel-loader parameter to load components on demand.

At present, many front-end projects are developed by single-page application, but with the continuous expansion of business, it will face a serious problem — the amount of code loaded for the first time will become more and more, affecting the user experience.

Import (*) statements control loading timing, and Webpack has built-in parsing of import(*), which generates a chunk from the module introduced in import(*) as a new entry. When the code executes to the import(*) statement, it loads the files generated by Chunk. Import () returns a Promise object, so in order for browsers to support it, you need to inject the Promise Polyfill beforehand

Refer to the article

  • What are the interview questions about Webpack?
  • Webpack Interview FAQ for front-end interviews
  • Simple Webpack electronic edition
  • Webpack builds a summary of performance optimization strategies