Home > Web Front-end > JS Tutorial > 10 webpack interview questions, how many can you answer?

10 webpack interview questions, how many can you answer?

青灯夜游
Release: 2021-09-16 10:37:48
forward
7309 people have browsed it

This article will share with you 10 interview questions about webpack. Check for any gaps and fill them in. How many of these ten interview questions can you answer correctly? Can you get them all correct?

10 webpack interview questions, how many can you answer?

The interview questions are just an introduction, Quickly brushing the questions is just memorizing (the interviewer will ask you, but he may not be very in-depth), think It still takes a lot of effort to understand deeply;

What is the construction process of webpack

  • Initialization parameters: Parse the webpack configuration parameters, merge the parameters passed in by the shell and configured in the webpack.config.js file to form the final configuration result;

  • Start compiling: Obtained from the previous step Initialize the compiler object with the parameters, register all configured plug-ins, the plug-in listens to the event nodes of the webpack build life cycle, reacts accordingly, and executes the run method of the object to start compilation;

  • Determine the entry: From the configured entry, start parsing the file to build the AST syntax tree, find the dependencies, and go on recursively;

  • Compile module: In the recursion, according to the file type and loader configuration, all configured loaders are called to convert the files, and then the modules that the module depends on are found, and this step is recursed until all the entry-dependent files have been processed by this step;

  • Complete module compilation and output: After the recursion is completed, each file result is obtained, including each module and the dependencies between them, and code is generated based on the entry or subcontracting configuration. Block chunk;

  • Output completed: Output all chunks to the file system;

Webpack’s hot Update principle

In fact, I opened the express application, added monitoring of webpack compilation, added a long websocket connection with the browser, and triggered webpack to compile when the file changes And after completion, will tell the browser through sokcet message to prepare to refresh . In order to reduce the cost of refreshing, does not need to refresh the web page, but refreshes a certain module, webpack-dev-server can support hot update, and compare it through the hash value of the generated file For modules that need to be updated, the browser will perform hot replacement

Server

  • Start the webpack-dev-server server
  • Create a webpack instance
  • Create server server
  • Add webpack’s done event callback
  • Send a message to the client after compilation is completed
  • Create express application app
  • Set the file system to the memory file system
  • Add webpack-dev-middleware middleware
  • The middleware is responsible for returning the generated file
  • Start webpack compilation
  • Create http server and start the service
  • Use sockjs to establish a long websocket connection between the browser and the server
  • Create a socket server

Client

  • webpack-dev-server/client will monitor this hash message
  • After receiving the ok message, the client will execute the reloadApp method to update
  • In reloadApp, it will be judged whether hot update is supported. If it is supported, the webpackHotUpdate event will occur. If it is not supported, the browser will be refreshed directly.
  • The webpackHotUpdate event will be monitored in webpack/hot/dev-server.js
  • The module.hot.check method will be called in the check method
  • HotModuleReplacement.runtime requests Manifest
  • Call JsonpMainTemplate by calling the hotDownloadManifest method of JsonpMainTemplate.runtime
  • . The hotDownloadUpdateChunk method of runtime obtains the latest module code through JSONP request
  • The patch js is retrieved or the webpackHotUpdate method of JsonpMainTemplate.runtime.js is called
  • Then the hotAddUpdateChunk method of HotModuleReplacement.runtime.js is called Dynamically update the module code
  • Then call the hotApply method for hot update

webpack packaging is how the hash code is generated

1. webpack There are many ways to calculate hash in the ecosystem

  • hash
  • chunkhash
  • contenthash

hash represents the hash value generated in each webpack compilation. All files using this method have the same hash. Each build causes webpack to calculate a new hash. Chunkhash is formed based on the entry file and its associated chunk. Changes to a certain file will only affect the hash value of the chunk associated with it, but will not affect the contenthash creation of other files based on the file content. When the file content changes, the contenthash changes

2. Avoid the same random value

  • webpack splits the chunk after calculating the hash. The same random value may be generated because these files belong to the same chunk. You can mention a file to an independent chunk (such as putting it into entry)

webpack offline How to cache static resources

  • When configuring webpack, we can use html-webpack-plugin to inject a script into html to statically store third-party or shared resources in Inject a tag into html, such as <% HtmlWebpackPlugin.options.loading.html %>. In html-webpack-plugin, you can inject script into it by configuring html attributes
  • Use webpack-manifest-plugin and configure webpack-manifest-plugin to generate a manifestjson file to compare the differences in js resources and decide whether to replace them. Of course, you must also write a cache script
  • When we do Cl When using CD, you can also inject static scripts by editing the file stream to reduce the pressure on the server and improve performance.
  • You can dynamically inject through periodic functions such as custom plugins or html-webpack-plugin. Front-end static storage script

webpack What are the common plugins

  • ProvidePlugin: Automatically load modules, replacing require and import
  • html-webpack-pluginCan automatically generate html code based on the template, and automatically reference css and js files
  • extract-text-webpack-plugin Extract styles referenced in js files into css files
  • DefinePlugin Configure global variables at compile time, which is very useful for allowing different behaviors in development mode and release mode builds.
  • HotModuleReplacementPlugin Hot update
  • optimize-css-assets-webpack-plugin Duplicate css in different components can be quickly removed
  • webpack-bundle-analyzer A webpack bundle file analysis tool that displays bundle files in the form of interactively zoomable treemaps.
  • compression-webpack-plugin The production environment can use gzip to compress JS and CSS
  • happypack: Accelerate code construction through a multi-process model
  • clean-wenpack-plugin Clean up unused files under each package
  • speed-measure-webpack-plugin: You can see to U each The execution time of each Loader and Plugin (the time of the entire package, the time of each Plugin and Loader)
  • webpack-bundle-analyzer: Visualize the volume of Webpack output files (business components , Rely on third-party modules

How to implement webpack plug-in

  • The essence of webpack is an event streaming mechanism, the core module: tabable (Sync Async) Hooks Construct === Compiler (compile) Compiletion (create bundles)
  • The compiler object represents the complete webpack environment configuration. This object is created once when starting webpack, and all operable settings are configured. Including options, loader and plugin. When applying a plug-in in the webpack environment, the plug-in will receive a reference to this compiler object. You can use it to access the main environment of webpack
  • The compilation object represents a resource version build .When running the webpack development environment middleware, whenever a file change is detected, a new compilation will be created, thereby generating a new compiled resource. A compilation object represents the current module resources, compiled resources, and changed resources. files, and information about the status of tracked dependencies. The compilation object also provides many key timing callbacks for the plug-in to choose when doing custom processing.
  • Create a plug-in function and define the apply method on its prototype , specify an event hook of webpack itself
  • The function internally processes the specific data of the internal instance of webpack
  • After the processing is completed, call the callback function provided by webpack
function MyWebpackPlugin()(
};
// prototype 上定义 apply 方法
MyWebpackPlugin.prototype.apply=function(){
// 指定一个事件函数挂载到webpack
compiler.pluginCwebpacksEventHook"funcion (compiler)( console. log(“这是一个插件”);
// 功能完成调用后webpack提供的回调函数
callback()
})
Copy after login

What are the commonly used Loaders in webpack

  • file-loader: Output the file to a folder, and reference the output through a relative URL in the code File
  • url-loader: Similar to file-loader, but can inject the file content into the code in base64 when the file is very small.
  • source-map-loader: Load additional Source Map files to facilitate breakpoint debugging
  • image-loader: Load and Compress image files
  • babel-loader: Convert ES6 to ES5
  • css-loader: Load CSS, support modularization, Features such as compression and file import
  • style-loader: Inject CSS code into JavaScript and load CSS through DOM operations.
  • eslint-loader: Check JavaScript code through ESLint

How webpack implements persistent caching

  • The server sets the http cache header(cache-control)
  • Package dependencies and runtime into different chunks, that is, as splitChunk, because they are almost unchanged
  • Lazy loading: Using import() method, dynamically loaded files can be divided into independent chunks to get their own chunkhash
  • Keep the hash value stable: Changes in the compilation process and file intercommunication should try not to affect the calculation of hashes of other files. For the unstable issue of incremental digital IDs generated by lower versions of webpack, you can use hashedModuleIdsPlugin to generate based on file paths.

How to optimize front-end performance with webpack?

Using webpack to optimize front-end performance means optimizing the output of webpack so that the final packaged result runs quickly and efficiently in the browser.

  • Compress code: Remove redundant code, comments, simplify code writing, etc. You can use webpack's UglifyJsPlugin and ParallelUglifyPlugin to compress JS files, and use cssnano (css-loader?minimize) to compress css
  • Use CDN to accelerate: During the build process, the css file will be compressed. Change the static resource path used to the corresponding path on the CDN. You can use webpack's output parameter and the publicPath parameter of each loader to modify the resource path
  • Tree Shaking: Delete the segments that will never be seen in the code. You can achieve this by appending the parameter --optimize-minimize when starting webpack.
  • Code Splitting: Divide the code into chunks according to routing dimensions or components, so that it can be loaded on demand. At the same time, you can make full use of the browser cache
  • to extract public third-party libraries: SplitChunksPlugin plug-in to extract public modules. The browser cache can be used to cache these for a long time without frequent changes. The public code

The principle of webpack treeShaking mechanism

  • treeShaking is also calledtree-shaking optimization, which is a method of moving Except for more code, to optimize the packaging volume, is enabled by default in the production environment .
  • You can analyze the unnecessary code when the code is not running;
  • Use the es6 module Specification
    • ES6 Module is introduced for static analysis, so correctly determine which modules are loaded during compilation
    • statically analyze the program flow and determine which modules Modules and variables are not used or referenced, and the corresponding code is deleted

Original address: https://juejin.cn/post/7002839760792190989

Author: Front-end_Maverick_to Rhino

Related tutorial recommendations: "Webpack Getting Started Video Tutorial"

The above is the detailed content of 10 webpack interview questions, how many can you answer?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:掘金--前端_小牛_到犀牛
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template