preface

  • The interview questions are just a lead-in,Quick brush is back(The interviewer asks you, but he doesn’t have to go very far),It takes a lot of effort to understand;

What is the webPack build process

  • Initialization parameters: parses webpack configuration parameters, merges the parameters passed in by shell and aligned with webpack.config.js file, and forms the final configuration result;

  • Start compiling: The parameter obtained in the previous step initializes the Compiler object and registers all configured plug-ins. The plug-in listens to the event node of the WebPack build life cycle and reacts accordingly. The run method of the object is executed to start compiling.

  • Determine the entry: from the entry of the configuration, start parsing the file to build the AST syntax tree, find out the dependencies, recursively;

  • Compiling modules: In recursion, according to the file type and Loader configuration, all configured Loaders are called to convert files, and then the modules that the module depends on are found, and this step is recursed again until all the files that rely on entry are processed by this step.

  • Complete module compilation and output: after recursion, get the result of each file, including each module and the dependencies between them, generate chunk of code according to entry or subcontracting configuration;

  • Output complete: Output all chunks to the file system.

Hot update principle for Webpack

When the file changes trigger webpack to compile and complete, the sokcet message will tell the browser to prepare to refresh. In order to reduce the cost of refreshing, that is, refreshing a module instead of refreshing a web page, webpack-dev-server can support hot update, which generates hash values of files to compare the modules that need to be updated, and then the browser performs hot replacement

The service side

  • Start the webpack-dev-server
  • Create a WebPack instance
  • Creating a Server
  • Add webpack’s done event callback
  • The message is sent to the client after compilation
  • Create the 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 files
  • Start webpack compilation
  • Create the HTTP server and start the service
  • Use SockJS to establish a websocket long connection between the browser and the server
  • Creating a Socket server

The client

  • The webpack-dev-server/client listens to the hash message
  • When the client receives an OK message, it performs the reloadApp method to update it
  • In reloadApp, it will determine whether hot update is supported. If it is supported, webpackHotUpdate event will occur. If it is not supported, it will directly refresh the browser
  • In webpack/hot/dev-server.js the webpackHotUpdate event is listened for
  • The module.hot.check method is called in the check method
  • HotModuleReplacement. Runtime to request the Manifest
  • By calling the JsonpMainTemplate. Runtime hotDownloadManifest method
  • Call JsonpMainTemplate. Runtime hotDownloadUpdateChunk method through the json request access to the latest module code
  • Patch can call JsonpMainTemplate js back or runtime. Js webpackHotUpdate method
  • Then call HotModuleReplacement. Runtime. Js hotAddUpdateChunk method dynamic update module code
  • The hotApply method is then called for heat recovery

How do webpack packages generate hash codes

1. There are multiple ways to compute hashes in the Webpack ecosystem

  • hash
  • chunkhash
  • contenthash

Hash represents the hash value generated in each Webpack compilation, and all file hashes using this approach are the same. Each build causes WebPack to compute the new hash. Chunkhash is generated based on the import file and its associated chunk. Changes in a file will only affect the hash value of the chunk associated with the file. Contenthash is created based on the content of the file. Contenthash changes when the contents of the file change

2. Avoid identical random values

  • Webpack inThe chunk is split after the hash is calculated.The same random value may be generated because the files belong to the same chunk, and a file can be referred to a separate chunk (such as entry).

How to implement webpack offline cache static resources

  • When configuring webpack, we can use the HTml-webpack-plugin to inject an HTML script to statically store third-party or shared resources in THE HTML to inject an identifier, for example<% HtmlWebpackPlugin.options.loading.html %>In htML-webpack-plugin, script can be injected by configuring HTML attributes
  • The manifestjson file is generated by configuring the Webpack-manifest-plugin, which is used to compare the differences between JS resources and whether to replace them. Of course, the cache script is also written
  • When we do Cl and CD, we can also achieve static script injection by editing the file stream to reduce the server pressure and improve the performance
  • Front-end static storage scripts can be dynamically injected through custom plugin or periodic functions such as HTMl-webpack-plugin

What are the common plugins for WebPack

  • ProvidePlugin: automatically loads modules instead of require and import
  • html-webpack-pluginYou can automatically generate HTML code from templates and reference CSS and JS files
  • extract-text-webpack-pluginSeparate styles referenced in the JS file into a CSS file
  • DefinePluginGlobal variables are configured at compile time, which is useful for development mode and release mode builds to allow different behavior.
  • HotModuleReplacementPluginHot update
  • optimize-css-assets-webpack-pluginDuplicate CSS in different components can be quickly de-duplicated
  • webpack-bundle-analyzerA Bundle file analysis tool for WebPack that presents bundles as interactively scaled Treemaps.
  • compression-webpack-pluginThe production environment can use GZIP compressed JS and CSS
  • happypack: Accelerate code construction through the multi-process model
  • clean-wenpack-pluginClean up unused files under each package
  • speed-measure-webpack-pluginU Implementation time of each Loader and Plugin (the total 扌 package time, the elapsed time of each Plugin and Loader)
  • webpack-bundle-analyzer: Visualizes the volume of Webpack output files (business components, dependent third-party modules)

How is the WebPack plug-in implemented

  • Tabable (Sync + Async)Hooks === Compiler + Compiletion
  • The Compiler object represents the complete Configuration of the WebPack environment. This object is created once when webPack is started, and all the 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 webPack environment
  • The compilation object represents a resource version build. When running the WebPack development environment middleware, each time a file change is detected, a new compilation is created, resulting in a new compilation resource. A compilation object represents the current module resources, compile-generated resources, changing files, and information about the state of the dependencies being tracked. The Compilation object also provides a number of critical timing callbacks that plug-ins can choose to use when doing custom processing
  • Create a plug-in function that defines the Apply method on its Prototype and specifies a WebPack event hook
  • The function handles the specific data of the webPack instance internally
  • When the processing is complete, call the callback function provided by WebPack
The function MyWebpackPlugin () (}; . / / the prototype is defined on the apply method MyWebpackPlugin prototype. Apply = function () {/ / specified function to an event to webpack mount Compiler. PluginCwebpacksEventHook funcion "(compiler) (the console. The log (" this is a plug-in"); // Webpack callback()})Copy the code

What are the common loaders for Webpack

  • 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 base64 inject file contents into code when 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: Converts ES6 to ES5
  • css-loader: Loads the CSS, supporting features such as modularization, compression, and file import
  • style-loader: Inject CSS code into JavaScript and load CSS via DOM manipulation.
  • eslint-loader: Checks JavaScript code with ESLint

How does WebPack implement persistent caching

  • The server sets the HTTP cache header(cache-control)
  • Package dependencies and runtimes into different chunks,SplitChunk, because they're pretty much constant
  • Lazy loadingUse:The import () method, files can be dynamically loaded into separate chunks to get their own chunkhash
  • Keep the hash value stable: Changes in the compilation process and in the file should not affect the hash calculation of other files. For unstable incremental digital IDS generated by earlier versions of WebPack, hashedModuleIdsPlugin can be used to solve the problem based on file path generation

How to usewebpackTo optimize front-end performance?

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.

  • The compression code: Remove unnecessary code, comments, simplify code writing, etc. 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
  • Tree Shaking: Removes fragments of code that will never go anywhere. This can be done by appending the parameter optimize-minimize when starting the Webpack
  • Code Splitting: Chunk the code into routing dimensions or components so that it can be loaded on demand while taking full advantage of the browser cache
  • Extract public third-party librariesSplitChunksPlugin plugin for common module extraction, using the browser cache can cache these common code for a long time without frequent changes

How the Webpack treeShaking mechanism works

  • Also called treeShakingShake the tree optimizationIs a way to optimize package size by removing more code,This function is enabled by default in the production environment.
  • Can be found inCode not runningIs analyzedUnneeded code;
  • usingEs6 moduleThe specification of the
    • The ES6 Module is importedStatic analysis, soDetermine which modules are loaded at compile time
    • Statically analyze the program flow to determine which modules and variables are not being used or referenced, and then remove the corresponding code

portal

  • Why do I insist on getting up at six
  • At 6 clock
  • Vite + React + TS
  • Vite + React + TS