Home  >  Article  >  Web Front-end  >  [Compilation and sharing] Some webpack interview questions (with answer analysis)

[Compilation and sharing] Some webpack interview questions (with answer analysis)

青灯夜游
青灯夜游forward
2023-03-01 19:58:144441browse

[Compilation and sharing] Some webpack interview questions (with answer analysis)

Talk about your understanding of Webpack

1.What is Webpack?

webpack is a static module packager. When webpack processes an application, it recursively builds a dependency graph that contains every module the application needs, and then packages these modules into one or Multiple bundles.

Webpack is like a production line. It must go through a series of processing processes (loaders) before the source files can be converted into output results. Each processing process on this production line has a single responsibility, and there are dependencies between multiple processes. Only after the current processing is completed can it be handed over to the next process for processing.
A plug-in is like a function inserted into the production line, which processes the resources on the production line at a specific time. Webpack will broadcast events during the running process. The plug-in only needs to listen to the events it cares about and can join the production line to change the operation of the production line.

2. Can you talk about the packaging process/building process
3.Can you talk about the optimization of front-end operation

The packaging process/packaging principle/building process of Webpack?

[Compilation and sharing] Some webpack interview questions (with answer analysis)
# The running process of webpack is a serial process, and its workflow is to connect various plug-ins in series.

Command line executionnpx webpackPackaging command starts
1.Initialize compilation parameters: Read and merge parameters from configuration files and shell commands
2.Start compilation: Initialize the Compiler object according to the parameters obtained in the previous step, load all configured Plugins, and execute the run method of the object to start compilation.
3.Determine the entry: Find all entry files according to the entry in the configuration
4.Compile module: Trigger from the entry file and call all configured Loader pairs The module is translated, and then the modules that the module depends on are found, and then this step is recursed until all the entry-dependent files are translated.
5.Complete module compilation: After using Loader to translate all modules in step 4, the final translated content of each module and the dependency graph between them are obtained.
6.Output resources: According to the dependency graph, assemble Chunks containing multiple modules, then convert each Chunk into a separate file and add it to the output list, and determine the output according to the configuration The path and file name are output.

In the above process, Webpack will broadcast specific events at specific points in time, and the plug-in will execute specific logic after listening to the events of interest.

Summary

  • Initialization: Read and merge parameters from configuration files and shell commands, initialize Compiler instances according to parameters, load Plugin (register all configured plug-in), call the run method of the Compiler instance to start compilation.

Compiler compilation object controls the webpack life cycle and does not perform specific tasks, but only performs some scheduling work. For example, perform module creation, dependency collection, chunking, packaging, etc.
After calling run, a Compiltation instance is created. Each build will create a new Compiltation instance, which contains the basic information of the build
Webpack Specific events will be broadcast at specific points in time, and the plug-in will execute specific logic after listening to the events of interest.

  • Compilation: Triggered from entry, each Module is serially called to the corresponding Loader to translate the module, and then the modules that the module depends on are found and compiled recursively.

Start parsing the file to build the AST syntax tree from the entry specified in the configuration file (webpack.config.js)

  • According to dependencies The graph is assembled into a chunk containing multiple modules, and each chunk is converted into a file for output.

Different entries generate different chunks, and dynamic import will also generate its own chunk

The role of loader in Webpack/ What is a loader?

Loader is webpack provides a mechanism to handle multiple file formats, because webpack only knows JS and JSON, so Loader is equivalent to a translator, converting other types of resources Perform preprocessing.
Used to convert the "source code" of the module.
The loader supports chain calls, and the order of calls is from right to left. **Each loader in the chain will process resources that have been processed before, and eventually become js code.
You can provide more capabilities to the JavaScript ecosystem through loader's preprocessing functions.

What are the common loaders?

  • less-loader: Compile less files into css files

During development, we often use the less preprocessor to write css styles. Improve development efficiency

  • css-loader: Turn the css file into a commonjs module and load it into js. The module content is the style string
  • style-loader: Create a style tag and load the style in js Insert the resource into the tag and add the tag to the head to take effect
  • ts-loader: Package and compile Typescript files

What does Plugin do? /What is Plugin

Plugin is more powerful, and its main purpose is to solve things that loader cannot achieve, such as packaging optimization and code compression.
After the Plugin is loaded, the functions defined by the plugin will be triggered at a certain point in the webpack build to help webpack do something. Implement functional extensions to webpack.

What are the common Plugins

  • html-webpack-plugin processes html resources and creates an empty HTML by default, automatically Introduce all the resources of the packaged output (js/css)
  • mini-css-extract-plugin The packaged css is in the js file. This plug-in can extract the css separately
  • clean-webpack -plugin Every time you package, the CleanWebpackPlugin plug-in will automatically delete the last package.

What is the execution order (loading mechanism) of the Webpack plug-in?

The difference between Loader and Plugin in Webpack

Always say
webpack is like a production line, which needs to go through a series of processes Only after the process (loader) can the source file be converted into an output result. Each processing process on this production line has a single responsibility, and there are dependencies between multiple processes. Only after the current processing is completed can it be handed over to the next process for processing.
A plug-in is like a function inserted into the production line, which processes the resources on the production line at a specific time. Webpack will broadcast events during the running process. The plug-in only needs to listen to the events it cares about and can join the production line to change the operation of the production line.

Or use the previous summary to explain what Loader and Plugin are respectively

Running timing
1. The loader runs in the compilation phase
2. Plugins work throughout the entire cycle
[Compilation and sharing] Some webpack interview questions (with answer analysis)

Usage method
Loader: 1. Download 2. Use
Plugin: 1. Download 2 .Quote 3. What optimization methods have been done using

#Webpack? What optimization methods are there?

How to use webpack to optimize front-end performance? The question is about production environment optimization
How to improve the build speed of webpack? The question is about optimization of build speed

tree-shaking Delete unused code to optimize front-end performance/increase build speed

tree-shaking is A kind of Dead Code Elimination technology packaging based on the ES Module specification. During the packaging process, modules that have not been referenced in the project are detected and marked, and the modules that have not been referenced are deleted, which improves the build speed and reduces the program running time.

What should you pay attention to when using tree-shaking?

1. Default mode = production, the tree-shaking function is enabled by default in the production environment.
2. Module code needs to be written using ES6 specifications. ES6 module dependencies are deterministic and have nothing to do with runtime status.
3. Try not to write code with side effects. For example, you have written an immediate execution function, used external variables in the function, etc.

About side effects

How to use webpack to optimize front-end performance?

  • Code compression

On-demand loading

  • Code split splitChunks - in the optimization configuration item Configuration

1. You can package the code in node__mudules separately into a chunk output (for example, using jqury?)
2. It will automatically analyze whether there are any common ones in the multi-entry chunk Files, if any, will be packaged into a separate chunk and will not be packaged repeatedly

  • Use Dll for sub-packaging

Under normal circumstances node_module will be Package into a file
Use dll technology to package frameworks and libraries that are not frequently updated separately and generate a chunk

  • Use routing to lazy load

All modules referenced by the import() function in the code will be packed into a separate package and placed in the directory where the chunk is stored. When the browser runs this line of code, it will automatically request this resource and implement asynchronous loading.

#How does Webpack configure compression code? What is compressed?

1. Configure the plug-in as a compressor for compression in the optimization configuration item.
2. Use this plug-in for compression in plugins

js compression: using terser-webpack-plugin
css compression: using optimize-css-assets -webpack-plugin plug-in

Removed console, comments, spaces, line breaks, unused css code, etc.

How to improve the build speed of webpack?

Idea 1: Reduce the files or codes that need to be built

  • HMR (Hot Module Replacement) module hot replacement only rebuilds the changed modules – in the development environment
  • Narrow the processing scope: Make reasonable use of these two attributes exclude: files that do not need to be processed and include: files that need to be processed
  • When the babel cache is built for the second time, the previous cache will be read, only Rebuild the changed files
  • Use Dll for subpackaging--> Subpackaging is convenient for on-demand loading

Normally node_module will be packaged into a file
Using dll technology, you can package those frameworks and libraries that are not frequently updated separately to generate a chunk
The project source code also needs to be split, and the packaged files can be divided according to routing--> How to implement routing lazy loading ? How to implement asynchronous loading of components in webpack?

Idea 2: Build in multiple processes

  • Package thread-loader in multiple processes and place it before the time-consuming loader

Process startup and process communication have overhead, and the working time is relatively long, so multi-process packaging is required

[Related recommendations: javascript video tutorial, programming video

The above is the detailed content of [Compilation and sharing] Some webpack interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete