5~10 questions are updated daily

directory

Has been finished

  • Module federal
  • How does Prerender pre-render work?
  • Can you explain the prerender-SPa-plugin in more detail?
  • Talk about tree-shaking
  • How are plugins in WebPack implemented?
  • What does Webpack do? Is there any customization done with the Webpack build?
  • How does dev-server run?
  • Webpack hot update principle
  • How do you organize CSS in a project?
  • How does WebPack cache static resources offline with localStorage?
  • How to implement WebPack persistent cache?
  • How is the Hash code generated when webpack is packaged? How can I avoid the same situation with random values?
  • What exactly does scaffolding do, and what configuration does Webpack do? How to optimize package size?
  • Webpack packaging is too large, how to optimize the volume?
  • What does Webpack do with dependencies in node_modules when using import?
  • What is the difference between Import and CommonJs in the WebPack packaging process
  • What is the webPack build process?
  • What is the difference between a Loader and a Plugin?
  • What is the difference between csS-loader and style-loader, file-loader and url-loader in Webpack?
  • Common loaders and summary of their functions
  • Common plugins and a summary of what they do

Module federal

  • With module federation, each part will be a separate build that is compiled toThe container
  • Containers can be referenced by applications or other containers
  • In this relationship, the container isThe remoteThe user of the container isThe host
  • The remoteYou can expose modules toThe host
  • The hostYou can use such modules, which are calledRemote module
  • By using a separate build, we can get good build performance for the entire system

How does Prerender pre-render work?

After the webpack is packed and the file is generated (after-emit Hook), a server simulation site is launched to access the specified page route using the puppeteer. Get the corresponding HTML structure, and output the result to the specified directory, the process is similar to crawler.

We pre-render the application using the packaging tool so that the user can see our content when they first get the HTML file, and then wait for the Bundle to complete the download parsing before taking over.

What is the core principle behind packaging to build pre-renders?

In fact, the headless browser is used to help achieve this function. It will launch a headless browser locally, access our configured route, and then output the HTML content of the rendered page to our HTML file, and create the relevant directory

Popular headless browsers such as Phantomjs and Puppeteer, for example, pre-render phantomjs internally as a headless browser.

Application scenarios

  • Seo optimization: Dynamic data can also be pre-rendered using renderAfterTime. As soon as the dynamic data is rendered, client code such as bundle.js takes over dom operations, making it easy to optimize for SPA
  • Skeleton screen: Use the skeleton screen as a pre-rendered page and replace it when Ajax gets the data; Prerende-spa-plugin provides the postProcessHtml hook

Pre-rendering is not suitable for frequently changing data, such as stock ticker sites or weather forecast sites. This is because the data is dynamic and the DOM nodes are already generated during pre-rendering. If you want to be compatible with SEO you can use SSR.

Pre-rendering is not suitable for large numbers of routing pages, such as hundreds or thousands of routes, and pre-rendering will be very slow after packaging.

The best application scenarios for pre-rendering are active pages that require SEO

advantages

  • Seo: For search engine crawlers (excluding advanced crawlers first), it will not wait for your JS execution to complete before crawling, if not pre-rendering, for client rendering applications, there is little content in the HTML file, so it will affect your search ranking. Using pre-render ensures that relevant HTML content is retrieved on the first load, which is good for SEO
  • Weak network environment: For users with poor network conditions, your bundle files are too large, which will cause the page to be blank for a long time. This will cause you to lose a lot of users, so it is important to render the content quickly for the first time.

Can you explain the prerender-SPa-plugin in more detail?

Using the plugin directly, you can configure routes that require pre-rendering:

By default, the HTML will be captured and output when the script is finished executing. You can also execute some hooks and the HTML will be captured at certain times.

const path = require('path');
const PrerenderSpaPlugin = require('prerender-spa-plugin');
// TODO...
{
  plugins: [new PrerenderSpaPlugin({
      path.resolve(__dirname,'./dist'),'/home'.'/foo'] and {// When listening to a custom event
        captureAfterDocumentEvent: "custom-post-render-event".// When the specified element is found
        captureAfterElementExists: "#content".// Timed capture
        captureAfterTime: 5000}}})]Copy the code

Once configured, we can find the pre-rendered HTML file for the route in our dist directory

dist
  - index.html
  - home
    - index.html
  - foo
    - index.html
Copy the code

Change the routing mode to history mode

disadvantages

Because of the construction of a pre-rendered by packaging tools render out when I was in the packaging, so if not rebuilt, so users can see pre-rendered page is always remains the same even if your page data update, early first rendering, but browser display is still the old data, If you want to see the latest data, you need to wait for js to download and re-render before it appears, which makes the user feel very awkward

Not only did we have to increase the configuration cost due to the power of packaging tools, but pre-rendering also lengthened the total packaging time and slowed down the speed of each build, which was a terrible development experience

Talk about tree-shaking

Tree-shaking is a technique that optimizes the size of a project’s packaging by removing redundant code

Tree-shaking

When the current project reaches a certain scale, we usually organize the code in a modular way, which can facilitate the organization and maintenance of the code. There is a problem, however, if we have an Utils utility class and import it in another module. This will also package unnecessary code in utils at packaging time, making the packaging larger. This is where Tree shaking technology is needed

The principle of

  • Make use of the features of ES6 modules

    • Can only appear as a statement at the top level of a module
    • The module name of import must be a string constant and cannot be imported dynamically into the module
    • The concept of tree-shaking was introduced in 1990, but it wasn’t really taken advantage of until ES6’s ES6-style modules came along.This is because tree-shaking only works in static modules. ES6 module loading is static, so using tree-shaking in ES6 is very easy. Furthermore, tree-shaking supports not only the import/export level, but also the declaration level

Before ES6, we could import the module require() using CommonJS. This import was dynamic, which meant we could import the required code based on conditions:

let mainModule; If (condition){mainModule=require('dog')}else{mainModule=require('cat')}Copy the code

The dynamic nature of CommonJS means tree-shaking doesn’t work. Because it is impossible to determine which modules are needed or not before they actually run. In ES6, a completely static import syntax is introduced: import.

If (condition){mainModule=require('dog')}else{mainModule=require('cat')}Copy the code

Conditional fetching can only be done by importing all packages

import dog from 'dog';
import cat from 'cat';
if(condition){
//dog.xxx
}else{
//cat.xxx
}
Copy the code

The IMPORT syntax of ES6 can be tree-shaking because it is possible to analyze unwanted code when it is not running.

How to use it?

Tree-shaking is implemented starting with WebPack2. The official version of Webpack2 has built-in ES6 module support (also called Harmony module) and unreferenced module detection. The official version of WebPack4 extends this detection capability by using the sideEffects property of package.json as a tag to give complier a hint as to which files in the project are ES6 modules, so it is safe to remove unused parts of the files if using WebPack4. To turn tree-shaking on, just set mode to production

entry: './src/index.js'.mode:'production'.output: {path: path.resolve(__dirname,'dist'),
    filename: 'bundle.js'
},
Copy the code

If you use Webpack2, you may find tree-shaking doesn’t work. Because Babel compiles code into CommonJS modules, and tree-shaking does not support CommonJS, you need to configure it not to escape

options: {
    presets: [['es2015',
            {
                modules: false}}]]Copy the code

About side effects

Side effects are those that perform some action when importing, but do not necessarily have any export. For example, ployfill, ployfill does not expose methods to the main program

Tree-shaking does not automatically recognize which code is a side effect, so it is important to specify it manually; if you do not specify it, some unexpected problems may occur

In Webpack, this is done through the sideEffects property of package.json

"name": "tree-shaking"."sideEffects": false
Copy the code

If none of the code contains side effects, we can simply flag this property as false to tell WebPack that it can safely remove unused export exports.

If your code does have some side effects, you can provide an array instead:

"name": "tree-shaking"."sideEffects": [
    "./src/public/polyfill.js"
]
Copy the code

conclusion

  • Tree-shaking does not support dynamic imports (like CommonJS require() syntax), only static imports (ES6 import/export)
  • In webpack, you can manually specify sideEffects by adding a “sideEffects” property to the project package.json file

How are plugins in WebPack implemented?

Implementation analysis

  • Webpack is essentially an event flow mechanism with core modules:tapable(Sync + Async)HooksCompiler + Compilation(create bundles)
  • 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, defines the Apply method on its Prototype, specifying an event hook for WebPack itself
  • The function handles the specific data of the webPack instance internally
  • When the processing is complete, call the callback function provided by WebPack
function MyWebpackPlugin(){
    //
};
// prototype defines the apply method
MyWebpackPlugin.prototype.apply = function(){
    // Specify an event function to mount to webpack
    compiler.plugin("webpacksEventHook", funcion (compiler){
        console.log("This is a plug-in.");
        // A callback function provided by Webpack after the function is called
        callback()
    })
}
Copy the code

What does Webpack do? Is there any customization done with the Webpack build?

What does Webpack do?

  1. Webpack is essentially just a static wrapper for JS reference programs. It can recursively build a file dependency graph based on file dependencies, and finally package files into one or more bundles.
  2. Webpack identifies which modules are the entry points to build packaging based on entry
  3. Webpack is based on Output, which outputs the build-packed files to a specified directory
  4. Starting from the entry file, call all configured Loader to translate the module, and then find the module that the module depends on, and thenrecursiveThis step knows that all import-dependent files have been processed in this step
  5. After all modules are translated by Loader, the final content of each module after translation and the dependencies between them are obtained. According to the dependency relationship between the entry and modules, the chunks containing multiple modules are assembled one by one, and then each chunk is converted into a separate file and added to the output list

Do you have any custom operations when webpack is built

  1. alias: Specifies an alias, which to some extent reduces the difficulty of developing the file path input, cache path can improve some packaging speed
  2. Module adds fallback to loader processing, can successively perform the specified pre-processing or post-processing in loader processing. Custom Loader components can also be specially replaced here
  3. optimization-splitChunks-cacheGroupsCustomize the performance optimization part of the package, the split, identification and extraction of the shared module after the specified part
  4. Custom plugins configuration:
    • CopyWebpackPlugin makes a copy of a static file
    • The ProgressBarPlugin packages monitoring of progress
    • HappyPack multithreaded packaging and so on
  5. Stats adjusts the console's output during packaging, detailed to the size of each file, time, packaging status and other display optimization
  6. devServer-before: Add pre-package optimizations to achieve more concise mock data

How does dev-server run?

Dev-server runs the configuration

  • The installationwebpack-dev-serverThe NPM package
  • Do the configuration in webpack.config.js

Common configuration object properties in devServer are as follows

  1. contentBase: "./"The local server in which directory to build the page, generally in the current directory
  2. HistoryApiFallback: true,It will be used when building spa applications. It uses the HTML5 History Api, and any jump or 404 response can point to the index.html page
  3. The inline: true,Webpack has two modes to support automatic refresh of dev-server, one is iframe mode, one is inline mode; No configuration is required in devServer to use iframe mode. Just use a specific URL format to access it; However, we usually use inline mode. If we set inline to true in devServer, we still need to configure inline to take effect when we start webpack-dev-server
  4. hot: trueEnable the WebPack hot module replacement feature
  5. portPort number (default 8080)

How did it run

  1. Starting the HTTP Service
  2. When WebPack is built, bundles are exported to memory, from which the HTTP service reads the Bundle files
  3. Listen for file changes and repeat the second step

Dev-server is actually an HTTP server, so you can also do static resource access and API Proxy code

Static resource access

{
    devServer:{
        contentBase:'public'
    }
}
Copy the code

The Proxy agent

{
    devServer:{
        proxy:{
            '/api':{
                target:'http://api.target.com'
            }
        }
    }
}
Copy the code

Webpack hot update principle

Basic concept

  1. Webpack Compiler: Compiles JS into bundles

  2. Bundle Server: Provides access to files in the browser, which is essentially a Server

  3. HMR Server: outputs hot updated files to the HMR Runtime

  4. HMR Runtime: it is injected into bundle.js, linked with HRM Server via webSocket, receives file changes and updates corresponding files

  5. Bundle.js: Build the output file

The principle of

1. Startup phase

  • The Webpack Compiler packages the corresponding file as bundle.js(including the injected HMR Server) and sends it to Bundler Server
  • The browser accesses the server to get bundle.js

2. Update phase (file changes)

  • The Webpack Compiler is recompiled and sent to the HMR Server
  • The HMR Server can know which resources and modules are changed and notify the HMR Runtime
  • HRM Runtime updates the code

Detailed explanation of HMR principle

Use webpack-dev-server to start the local service. Internal implementation only uses WebPack, Express, and webSocket

  • Start the local service with Express and respond when the browser accesses the resource

  • The server and client use Websocket to implement long connections

  • Webpack listens for changes to the source file, triggering a webPack recompile when the developer saves the file

    • Each compilation generates hash values, JSON files that have changed the module, and JS files that have changed the module code
    • After compiling, push the current compiled hash stamp to the client through the socket
  • The websocket on the client listens for the hash stamp pushed by a file change and compares it with the last one

    • Consistency goes cache
    • If not, get the latest resources from the server through Ajax and JSONP
  • Use an in-memory file system to replace modified content for a partial refresh

The server 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 side

  • 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 hot updates

How do you organize CSS in a project?

In our daily use of CSS organizations, CSS-loader, style-loader is essential. So how do you organize CSS in general?

cssModule

You can enable modularization by configuring modules in css-loader to prevent className pollution and implement CSS localization. Disadvantages: the generated className semantics are reduced

postCss

It integrates CSS-Next, autoprefix, CSS in JS, CSS Module and many other features. It is optional and user-friendly

less\sass\stylus

CSS preprocessors add programming features that don’t have to worry about compatibility. You can use variables, functions, and so on, but postCss supports them all.

How does WebPack cache static resources offline with localStorage?

  1. When configuring webpack, we can use the HTml-webpack-plugin to inject and HTML a script to store third-party or shared resources statically. For example, < % % HtmlWebpackPlugin. The options. Loading. HTML >, can be configured in the HTML – webpack – plugin HTML attributes, the script injected into it

  2. Using webpack-manifest-plugin and through the configuration of webpack-manifest-plugin, generate manifest.json file, used to compare the difference of JS resources, do whether to replace, of course, also need to write cache script

  3. When we do CI and CD, we can also edit the file stream to achieve static script injection, to reduce the server pressure and improve performance

  4. Front-end static storage scripts can be dynamically injected through custom plugin or periodic functions such as HTMl-webpack-plugin

How to implement WebPack persistent cache?

1. Strong cache

Server set HTTP Cache headers (cache-control, etc.)

2. Package dependencies and runtimes separately

Pack dependencies and runtimes into different chunks (in Webpack, separate compiled files are called chunks), called splitchunks, because they are almost constant

3. Subcontracting loading (delayed loading)

Using import(), dynamically loaded files can be split into separate chunks to get their own chunkhash

4. Ensure the hash value is stable

Changes to the compilation process and file contents should not affect the hash calculation of other files. The problem of unstable incremental digital ids generated by earlier versions of WebPack can be solved by HashedModuleldsPlugin based on file path generation

How is the Hash code generated when webpack is packaged? How can I avoid the same situation with random values?

  • 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 only affect the hash value of the chunk associated with it, not other files

  • Contenthash is created based on the contents of the file. Contenthash changes when the contents of the file change

Avoid identical random values

Webpack splits the chunk after computing the hash.

The same random value may be generated because these files belong to the same chunk and can be referred to a separate chunk(such as entry).

What exactly does scaffolding do, and what configuration does Webpack do? How to optimize package size?

What scaffolding does

  • Create a VUE project demo
  • Build the basic WebPack configuration
  • Set up the babelrc basic configuration
  • Determine whether to help set up vue-router by setting
  • Whether to help configure ESLint
  • Whether to help configure the CSS preprocessor
  • Help configure the unit testing tool Karma+Mocha
  • Whether to help install e2E for user behavior simulation tests

Help you build the foundation for your project

What configuration does WebPack do?

  • Hot update
  • The agent
  • translation
  • Compressed package
  • Automatically upload

Enable multi-core compression terser-webpack-plugin

const TerserPlugin = require("terser-webpack-plugin"); module.exports = { optimization: { minimizer: [ new TerserPlugin({ parallel: true, terserOptions: { ecma: 6,},}),],},};Copy the code

Monitoring panel speed-measure-webpack-plugin

Display the time spent by each loader and plugin during packaging for precision

// webpack.config.js const SpeedMeasurePlugin = require("speed-measure-webpack-plugin"); const smp = new SpeedMeasurePlugin(); / /... // Wrap the merged config module.exports = smp.wrap(merge(_mergeConfig, webpackConfig));Copy the code

Open a notification panel, webpack-build-notifier

/ / webpack. Config. Js file const WebpackBuildNotifierPlugin = the require (" webpack - build - notifier "); Const webpackConfig = {plugins: [new WebpackBuildNotifierPlugin ({title: "my webpack", / / logo: path.resolve('./img/favicon.png'), suppressSuccess: true, }), ], };Copy the code

Enable package progress-bar-webpack-plugin

// webpack.config.js const ProgressBarPlugin = require("progress-bar-webpack-plugin"); const webpackConfig = { plugins: [new ProgressBarPlugin()], };Copy the code

Development panel clearer WebPack-Dashboard

// webpack.config.js file const DashboardPlugin = require("webpack-dashboard/plugin"); const webpackConfig = { plugins: [new DashboardPlugin()], };Copy the code
Json file {"scripts": {"dev": "webpack-dashboard webpack --mode development",},}Copy the code

Open window title node-bash-title

This package applies to Mac items, but does not apply to Windows

// webpack.config.js const setTitle = require("node-bash-title"); setTitle("server");Copy the code

Configure the printed information friendly-errors-webpack-plugin

new FriendlyErrorsWebpackPlugin({
    compilationSuccessInfo: {
        messages: ['You application is running here http://localhost:3000'],
        notes: ['Some additionnal notes to be displayed unpon successful compilation']
    },
    onErrors: function (severity, errors) {
        // You can listen to errors transformed and prioritized by the plugin
        // severity can be 'error' or 'warning'
    },
    // should the console be cleared between each compilation?
    // default is true
    clearConsole: true,

    // add formatters and transformers (see below)
    additionalFormatters: [],
    additionalTransformers: []
}),
Copy the code

Webpack packaging is too large, how to optimize the volume?

Analyze performance bottlenecks with tools

Speed-measure-webpack-plugin (SMP for short) analyzes the time consuming of Loader and plugin during Webpack packaging, helping to find performance bottlenecks in the construction process.

According to the need to load

  • Routing components are loaded on demand
  • Third-party components and plug-ins. Load on demand Import third-party components
  • Plugins that are only used in individual components can also be introduced in components on demand rather than in main.js

The production environment closes sourceMap

Code compression

  • UglifyJS: Vue-CLI default code compression method, it uses single-threaded compression code, packaging time is slow
  • ParallelUglifyPlugin: Enable multiple sub-processes to compress files for multiple sub-processes

CDN optimization

  • As the project grows, it relies on more and more third-party NPM packages, and the files it builds become larger and larger.
  • Coupled with single-page applications, this can lead to long periods of blank screens on slow Internet speeds or with limited server bandwidth.

The compression code

webpack-paralle-uglify-plugin

Uglifyjs-webpack-plugin Enables parallel (ES6 not supported)

Terser-webpack-plugin Opens paraller parameter

Parallel compression of multiple processes

Extract Chunk CSS code into separate files via mini-CSS-extract-plugin

Enable CSSNano compressed CSS with the optimize- CSS -assets-webpack-plugin

Extract page common resources

The htMl-webpack-externals-plugin is used to import the basic package through the CDN and not into the bundle

SplitChunksPlugin (common scripts, base packages, page common files) separation (built-in webPack4) replaces the CommonsChunkPlugin

Base package separation: Put some base libraries into the CDN, such as VUE, Webpack configuration External is not bundled into vUE

Tree shaking

Disable module dependency resolution for Babel-loader, otherwise WebPack receives converted commonJS modules and cannot tree shaking

Use purgecss-Webpack-Plugin with Mini-CSS-extract-Plugin (just a suggestion)

Modules that are not referenced in the project are detected and marked during the packaging process, and removed from the final bundle when resources are compressed (only for ES6 Modules). Use ES6 Module modules whenever possible to improve tree Shaking efficiency

Use PurifyCSS(not in maintenance) or UNCSS to remove unwanted CSS code

Scope hoisting

The code you build will have a large number of closures, which will increase in size, create more scoped functions when you run the code, and increase memory overhead.

Scope puts all module code in a function Scope in reference order, and then appropriately renames some variables to prevent variable name conflicts

It must be ES6 syntax, because many third-party libraries still use CommonJS syntax. In order to make full use of Scope compensation, mainFields should be configured to use ES6 modular syntax pointed in JSNext: Main in preference to third-party modules

Image compression

Use Imagemin based on Node libraries (lots of customization options, multiple image formats)

Configuration image – webpack – loader

Dynamic Ployfill

It is recommended to use polyfill-service to return only the required polyfill to the user. Community maintenance.

Polyfills are dynamically loaded in @babel-preset-env with useBuiltIns:”usage” parameter

What does Webpack do with dependencies in node_modules when using import?

ES6 Module

Different from CommonJS and AMD’s module loading methods, ES6 implements module functions on the JS language level.

The idea is to be as static as possible so that module dependencies can be determined at compile time.

When the module load command import is encountered, the module is not executed, but only a reference is generated. Wait until you really need it, and then go to the module and evaluate it. This is the biggest difference from the CommonJS module specification.

What does Webpack do with dependencies in node_modules

Webpack determines the module type based on how the definition is introduced, and then compiles and transforms it.

When import is introduced, Babel converts ES6 modules to the CommonJS specification by default, and then packages dependencies in node_module as self-executing functions

  • Determine the import mode (import or require)
  • Compiled into
(function(modules){// execute logic})([module array])Copy the code

The module is passed in the module array and exported through module.exports through a series of operations in the function body

What is the difference between Import and CommonJs in the WebPack packaging process

1. Es6 module calls commonJS module

You can use commonJS modules directly. Commonjs modules will not be compiled by webPack’s module system and will be exported as is, and CommonJS modules have no default attribute

2. Es6 module invokes ES6 module

The es6 module being called does not add {esModule:true}, only the caller adds {esModule:true}, and tree-shaking is possible. If the ES6 module being called is only imported, but not used, The called ES6 module will be marked with /* unused Harmony default export */, which will be deleted when compressed (if the es6 module has immediate execute statements, they will be reserved).

The 3.com MonJS module references the ES6 module

Es6 modules are compiled to add {__esModule:true}. If the invoked ES6 module happens to have an export default statement, the compiled ES6 module will add the default attribute

4.commonjs module calls commonJS module

The CommonJS module will be output as-is

What is the webPack build process?

Concise version

The running flow of Webpack is a serial process, from start to finish the following process is performed - initialization parameters: read and merge parameters from configuration files and Shell statements to arrive at the final parameters - start compilation: Initialize the Compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the object's run method to start compiling. - Determine entry: locate all entry files according to the entry in the configuration. - Compiling module: starting from the entry file, call all configured Loader to translate the module, and then find out the module that the module depends on, and recurse this step until all the entry dependent files have gone through this step; - Complete module compilation: After the fourth step of using Loader to translate all modules, get the final content of each module after translation and the dependencies between them. According to the dependency between the entry and modules, the Chunk is assembled one by one containing multiple modules, and then each Chunk is converted into a separate file and added to the output list. This step is the last chance to modify the output content. - Output complete: After determining the output content, the output path and file name are determined according to the configuration, and the file content is written to the file system. In the above system, WebPack will broadcast a specific event at a specific point in time, and the plug-in will execute a specific logic after listening for the event of interest. And plug-ins can call the API provided by WebPack to change the running results of WebPackCopy the code

Webpack is a tool for packaging modular javascript that treats all files as modules. The conversion file is compiled by loader, the hooks are injected by plugin, and finally the output resource modules are combined into files. Its main configurations include entry, output, modules,plugins, and loader.

Basic Concepts:

  1. Compiler: The running entrance of Webpack. It defines the main process of Webpack construction during instantiation and the core object compilation used during creation.

  2. Compilation: Instantiated by the Compiler, it stores the data used in the build process. The user monitors the changes of these data and creates a Compilation instance for each build.

  3. Chunk: Generally, one entry corresponds to one chunk.

  4. Module: Identifies the type of code modules. There are subclasses for modules in different situations. Module details can be obtained from Module instances, such as Dependiqueues.

  5. Parser: Analyzes AST syntax tree based on Acorn, and parses the dependencies of code modules;

  6. Dependency: Resolve Dependency objects used to hold code blocks

  7. Template: Code module used to generate the final code

Basic process:

  1. To control the build process, create an instance of Complier that contains the basic WebPack environment information

  2. Convert the configuration item (webpack.config.js + shell script parameters) to the corresponding internal plug-in and initialize the Options configuration item

  3. Perform the compiler. The run

  4. Create a Complitation instance. Each build creates a Compilation instance that contains the basic information for that build.

  5. Recursively analyze the dependencies from entery, buildmodule for each module, and convert different types of modules into webpack modules through loader

  6. Call parser.parse to convert the above structure into an AST tree,

  7. The entire AST tree is traversed, collecting dependencies and saving them in the compilation instance

  8. Generates chunks, generates chunks for different entries, generates chunks for different entries, and dynamic imports generate chunks of their own, and then optimizes after chunks are generated

  9. Generate the resulting code using the Template compilation based data

Compilation process:

  • The first step is to initialize the parameters. Through args, the configuration information of webpack.config.js and shell script is combined and initialized.

  • The second step uses the initialized parameters to create a Complier object, which can be thought of as an instance of WebPack. Exists in the whole process of Webpack from start to finish, it contains webpack module, plugin and other parameter information, and then calls the complier.run method to start compiling.

  • The third step is to find the entry file based on the entry configuration information and create the Compilation object, which can be understood as a build compilation process of Webpack. Contains all resources for the current compilation environment. Includes compiled resources.

  • The fourth step is to call Loader to compile modules through configuration information and convert modules into AST trees using Acorn. When require module dependencies are encountered, create dependencies and add them to the dependency array. Then find out the dependencies of dependencies and process all dependencies recursively and asynchronously.

  • In the fifth step, after obtaining the dependencies of all modules and translated files of modules, the compilation.seal method was called to sort out these modules and chunks created according to the dependencies of modules, merge and split all resources, and finally modify the output contents once.

  • Step 6 Output the final module file according to the output configuration information, and specify the output file name and file path.

Principle:

The output file wrapped by WebPack is essentially a closure, passing in an object whose key is the path to all the output files and whose content is the contents of the eval wrapped file. The closure rewrites the loading mode of the module, and defines the webpack_require method to realize the loading mechanism of commonJS standard module.

Webpack is actually time-streamed and runs through a series of plugins that leverage hooks from the Tapable library to control each step of the build process.

What is the difference between a Loader and a Plugin?

1. 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.

2. Different usage:

  • Loader is configured in module.rules, that is, 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.

What is the difference between csS-loader and style-loader, file-loader and url-loader in Webpack?

  • Css-loader: processes CSS files
  • Style-loader: package the style file code imported from the JS import into the JS file. When running the JS file, the style will be automatically inserted into the<style></style>In the label
  • File-loader: returns the URL of the image
  • Url-loader: the limit attribute is used to process images. When the size of an image is smaller than limit(byte), the image is transferred to Base64. When the size is larger than limit, file-loader is used to process the image

Url-loader encapsulates file-loader, but url-loader does not depend on file-loader

Common loaders and summary of their functions

  • Raw-loader: load the raw content of the file (UTF-8)
  • 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 file contents into code base64 if the files are too small
  • Source-map-loader: Loads additional source map files to facilitate breakpoint debugging
  • Svg-inline-loader: Injects compressed SVG content into code
  • Image-loader: loads and compresses image files
  • Json-loader Loads a JSON file(Included by default)
  • Handlebars -loader: Compiles the Handlebars template into a function and returns it
  • Babel-loader: Convert ES6 to ES5
  • Ts-loader: Converts TypeScript to JavaScript
  • Awesome-typescript-loader: converts typescript to JavaScript with better performance than TS-Loader
  • Css-loader: loads the CSS and supports features such as modularization, compression, and file import
  • Style-loader: Inserts CSS code into JS and loads CSS through DOM manipulation
  • Eslint-loader: Checks JS code through ESLint
  • Tslint-loader: Checks TypeScript code using tsLint
  • Postcss-loader: extends the CSS syntax and uses the next generation CSS. It can work with the autoprefixer plug-in to automatically complete the CSS3 prefix
  • Vue-loader: loads vue. js single file components
  • Cache-loader: can be added before some loaders with high performance overhead to cache results to disks

Common plugins and a summary of what they do

  • Define -plugin: Define environment variables (Webpack4 after specifying mode is automatically configured)

  • Ignore-plugin: ignores some files

  • Commons-chunk-plugin: Extract common code

  • Html-webpack-plugin: Simplifies HTML file creation (dependent on html-loader)

  • Web-webpack-plugin: It is easier to output HTML for a single page application than the html-webpack-plugin

  • Uglifyjs-webpack-plugin: no SUPPORT for ES6 compression (pre-Webpack 4)

  • Terser-webpack-plugin: Supports compression of ES6 (Webpack4)

  • Mini-css-extract-plugin: Separate style files, extract CSS as separate files, support on-demand loading (alternative to extract-text-webpack-plugin)

  • Webpack-parallel-ugli-fi -plugin: Multiple processes perform code compression to improve build speed

  • Serviceworker-webpack-plugin: Adds offline caching for web applications

  • Clean-webpack-plugin: directory cleaning

  • ModuleConcatenationPlugin: open the Scope Hoisting

  • Speed-measure-webpack-plugin: you can view the execution time of each Loader and plugin (total packaging time, each plugin and Loader time).

  • Webpack-bundle-analyzer: Visualize the volume of webpack output files (business components, dependent third party modules)