Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions for webpack?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what are the interview questions about webpack, the editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

What is the construction process of webpack?

Initialization parameters: parse the webpack configuration parameters, merge the parameters passed in shell and those configured in the webpack.config.js file to form the final configuration result

Start compilation: the parameters obtained in the previous step initialize the compiler object, register all configured plug-ins, and the plug-in listens to the webpack build lifecycle event node, responds accordingly, and executes the object's run method to start compilation.

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

Compilation module: recursively call all configured loader to convert files according to file type and loader configuration, then find out the module that the module depends on, and then recurse this step until all the files that the entry depends on have been processed by this step.

Complete module compilation and output: after recursion, get the result of each file, including each module and their dependencies, and generate a code block chunk according to entry or subpackage configuration

Output complete: export all chunk to the file system

The Hot Renewal principle of webpack

In fact, I opened the express application, added listening for webpack compilation, and added a long websocket connection to the browser. When the file change triggers the webpack to compile and complete, it will tell the browser to prepare for refresh through the sokcet message. In order to reduce the cost of refreshing, that is, instead of refreshing the web page, webpack-dev-server can support hot updates. By generating the hash value of the file, the browser can hot replace the modules that need to be updated.

Server side

Start the webpack-dev-server server

Create a webpack instance

Create a server server

Add done event callback for webpack

After compilation, send a message to the client

Create an express application app

Set the file system to a memory file system

Add webpack-dev-middleware middleware

The middleware is responsible for returning the generated files

Start webpack compilation

Create a http server and start the service

Use sockjs to establish a websocket persistent connection between the browser and the server

Create a socket server

Client

The webpack-dev-server/client side will listen to this hash message

After receiving the ok message, the client will execute the reloadApp method to update

In reloadApp, it will determine whether hot updates are supported. If so, a webpackHotUpdate event occurs. If not, refresh the browser directly.

Listen for webpackHotUpdate events in webpack/hot/dev-server.js

The module.hot.check method is called in the check method

HotModuleReplacement.runtime request Manifest

By calling the hotDownloadManifest method of JsonpMainTemplate.runtime

Call the hotDownloadUpdateChunk method of JsonpMainTemplate.runtime to get the latest module code through JSONP request

Patch js may call the webpackHotUpdate method of JsonpMainTemplate.runtime.js to retrieve it.

Then the module code is dynamically updated by calling the hotAddUpdateChunk method of HotModuleReplacement.runtime.js

Then call the hotApply method for hot change

Webpack packaging is how hash codes are generated.

1. There are many ways to calculate hash in webpack ecology.

Hash

Chunkhash

Contenthash

Hash represents the hash value generated in each webpack compilation, and all files that use this method are the same hash. Each build causes webpack to calculate the new hash. Chunkhash is formed based on the entry file and its associated chunk, and changes to one file will only affect the hash value of the chunk associated with it, not the creation of other files based on the contents of the file. Contenthash changes when the contents of the file change

2. Avoid the same random value

Webpack divides the chunk after calculating the hash. The same random values may be generated because these files belong to the same chunk, and you can refer a file to a separate chunk (such as putting it in an entry)

How to implement webpack offline cache static resources

When configuring webpack, we can use html-webpack-plugin to inject into a script with html to store third-party or shared resources statically and inject an identity into html. For example, script can be injected into html-webpack-plugin by configuring the html attribute.

Use webpack-manifest-plugin and configure webpack-manifest-plugin to generate a manifestjson file, which is used to compare the differences of js resources, whether to replace or not, and, of course, to write cache script

When we do Cl and CD, we can also inject static scripts by editing the file stream to reduce the pressure on the server and improve performance.

You can dynamically inject static storage script into the front end by defining periodic functions such as plugin or html-webpack-plugin.

What are the common plugin of webpack

ProvidePlugin: automatically load modules instead of require and import

Html-webpack-plugin can automatically generate html code based on templates and automatically reference css and js files.

Extract-text-webpack-plugin extracts styles referenced in js files into css files separately.

DefinePlugin configures global variables at compile time, which is useful for building development mode and release mode to allow different behaviors.

HotModuleReplacementPlugin hot update

Duplicate css in different components of optimize-css-assets-webpack-plugin can be removed quickly.

Webpack-bundle-analyzer is a webpack bundle file analysis tool that displays bundle files in the form of interactively scalable treemap.

Gzip compression JS and CSS can be used in compression-webpack-plugin production environment.

Happypack: speed up code construction through a multi-process model

Clean-wenpack-plugin cleans up unused files in each package

Speed-measure-webpack-plugin: as you can see, each Loader and Plugin takes time to execute (the entire Plugin and Loader take time)

Webpack-bundle-analyzer: visualize the volume of the Webpack output file (business components, dependent on third-party modules

How to implement the webpack plug-in

Webpack is essentially an event flow mechanism. The core module: tabable (Sync + Async) Hooks constructs = Compiler (compile) + Compiletion (create bundles)

The compiler object represents the complete webpack environment configuration. This object is created at once when webpack is started, and all actionable settings are configured, including options, loader, and plugin. When a plug-in is applied in a webpack environment, the plug-in receives a reference to this compiler object. You can use it to access the main environment of webpack

The compilation object represents a build of the resource version. When running webpack development environment middleware, whenever a file change is detected, a new compilation is created, resulting in a new compilation resource. A compilation object represents the current module resources, compiled generation resources, changed files, and information about the state of the dependencies being tracked. The compilation object also provides many critical timing callbacks for the plug-in to choose to use when doing custom processing.

Create a plug-in function that defines an apply method on its prototype and specifies an event hook of webpack itself

The function handles the specific data of the internal instance of webpack

After processing, call the callback function provided by webpack

Define apply method MyWebpackPlugin.prototype.apply=function () on function MyWebpackPlugin () / prototype {/ / specify an event function to mount to webpackcompiler.pluginCwebpacksEventHook "funcion (compiler) (console. Log (" this is a plug-in "); / / what are the common Loader of webpack after the function is called callback ()} provided by webpack

File-loader: the output file is exported to several folders, and the output is referenced by relative URL in the code.

Url-loader: similar to file-loader, but can annotate the content of a piece into the code in the style of base64 in the case of a "piece".

Source-map-loader: load additional Source Map widgets to facilitate breakpoint debugging

Image-loader: load and compress graphics components

Babel-loader: convert ES6 to ES5

Css-loader: load CSS, support modularization, compression, hardware guide and other features

Style-loader: note the CSS code into the JavaScript and load the CSS through the DOM operation.

Eslint-loader: checking JavaScript code through ESLint

How to implement persistent caching in webpack

Server sets http cache header (cache-control)

Package dependencies and runtime to different chunk, that is, as splitChunk, because they are almost unchanged

Delayed loading: using import (), dynamically loaded files can be assigned to a separate chunk to get their own chunkhash

Keep the hash value stable: the compilation process and changes within the file will not affect the hash calculation of other files as far as possible. For the incremental digital id instability generated by the lower version of webpack, you can use hashedModuleIdsPlugin generation based on file path to solve the problem.

How to optimize front-end performance with webpack?

Optimized webpack frontend performance means to optimize the output of webpack to make the final packaged results work quickly and efficiently in browsers.

Compressed code: remove redundant code, comments, simplify the way the code is written, etc. You can use UglifyJsPlugin and ParallelUglifyPlugin of webpack to compress JS parts, and cssnano (css-loader?minimize) to compress css.

Facilitate CDN acceleration: during the construction process, modify the static resource path of the reference to the corresponding path on the CDN. You can modify the resource path by using webpack for output parameters and publicPath parameters for each loader.

Tree Shaking: delete sections in the code that will never be found. This can be achieved by appending the parameter optimize-minimize when starting webpack

Code Splitting: divide the code into chunk by routing dimension or component, so as to load on demand and make full use of browser cache

Extract the common third library: the SplitChunksPlugin plug-in is used to extract the common module, and the browser cache can cache the common code that needs to be changed frequently.

The principle of webpack treeShaking mechanism

TreeShaking, also known as shaking tree optimization, is a way to optimize packaging volume by removing more than code. The production environment is enabled by default.

You can analyze unwanted code when the code is not running

Using the specification of es6 module

ES6 Module is introduced for static analysis, so you can correctly judge which modules are loaded when compiling.

Statically analyze the program flow to determine which modules and variables are not used or referenced, and then delete the corresponding code

This is the end of the article on "what are the interview questions for webpack". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report