1. Webpack is a quick start

yarn add webpack-cli --dev Webpack / / installation
Copy the code
"scripts": {
    "build": "webpack"
  },
Copy the code

Add shortcut instructions to package so that you only need YARN Build for packaging each time

2. Webpack configuration file

Later versions of Webpack4 support 0 configuration packaging, and the whole process will follow the convention SRC /index as the entry of packaging, and the packaging results will be stored in dist/main.js. Create the webpack.congig.js file and write the configuration

const path = require('path')// Import the node pash module
module.exports = {
  entry: './src/main.js'.output: {
    filename: 'bundle.js'.// The output file name
    path: path.join(__dirname, 'output')// Get the full absolute path to output}}Copy the code

3. Webpack working mode

The use of a working mode has been added to Webpack4 to simplify the complexity of webPack configuration, which can be understood as several sets of preset configurations for different environments

const path = require('path')
module.exports = {
  // This property has three values: production, development, and None.
  // 1. In production mode, Webpack automatically optimizes the packaging result;
  // 2. In development mode, Webpack will automatically optimize the packaging speed and add some assistance during debugging;
  // 3. In None mode, Webpack runs raw packaging without any extra processing;
  mode: 'development'.entry: './src/main.js'.output: {
    filename: 'bundle.js'.path: path.join(__dirname, 'dist')}}Copy the code

4, Webpack packaging results running principle

Don’t understand,

5. Load the Webpack resource module

Loaders within Webpack can only handle JS files; if you want to handle other types of resource files, you need to add other loaders. Loader is the core of the modular realization of the whole front-end, through different Loaders, you can load any type of resources.To process CSS files, you need to install CSS-Loader

yarn add css-loader --dev
Copy the code

After the installation is complete, add the corresponding configuration in rules to the configuration file. If multiple Loaders are configured, perform the configuration from the back to the front

const path = require('path')

module.exports = {
  mode: 'none'.entry: './src/main.css'.output: {
    filename: 'bundle.js'.path: path.join(__dirname, 'dist')},module: {
    rules: [{test: /.css$/,
        use: [
          'style-loader'.'css-loader'}]}}Copy the code

6. Webpack imports the resource module

Dynamically import resources based on what the code needs. It’s not the application that needs the resources, it’s the code. Js drives the entire front-end application

7, Webpack loader set

Loader within Webpack can only process JS files. When it meets non-JS files, it needs to download other Loaders to convert them into JS codes and realize loading.

1. File resource loader (processing image resource files)

yarn add file-loader --dev 
Copy the code
module: {
    rules: [{test: /.png$/,
        use: 'file-loader'}}]Copy the code

File when the working process of the loader webpack packaging, met a picture file, according to the configuration in the configuration file, matching the corresponding file loader, file loader starts to work, first will import file, copied to the output directory, and then copy the file to the output directory path for the current module after the return value of the return, The required resources are published and then available through the module’s export members

2. The URL loader

Data URL is a special URL protocol that can be used to directly represent a file. Traditional URL requires the server to have a corresponding URL file, and then obtain the corresponding file on the server by requesting this address.

Data URLs are a way to represent the content of a file directly from the current URL. The text in the URL already contains the content of the file without any HTTP requests.

Best practices: Use Data URLs for small files to reduce requests and store large files separately for faster loading

yarn add url-loader --dev
Copy the code
module: {
    rules: [{test: /.png$/,
        use: {
          loader: 'url-loader'.options: {
            limit: 10 * 1024 // 10 KB handles files smaller than 10 KB in Data URLs
            // To use this limit, you must configure file-loader to use files that exceed the limit
            / / file - loader}}}]}Copy the code

8. Webpack commonly uses loader classification

1. Compile the conversion class

  • Converts loaded resource modules into JS code (CSS-loader)

2. File operation type

  • It copies the loaded resource module to the output directory and exports the access path of the file (file-loader).

3. Code check type

  • Check the code of the loader, the purpose is to unify the code style, improve the quality of the code

9. Webpack and ES2015

Webpck is just a packaging tool and does not handle new features in ES6 or later. If needed, you can install a specific loader to do so.

The loader can be used to compile the transformation code

10. Loading mode of Webpack module

Try not to mix these standards in your project, which reduces project maintainability; just use one.

Loading non-JS files by a loader also triggers resource loading

Almost all reference resources will be found by Webpack, and then handed to different loaders for processing according to the configuration. Finally, the result of processing will be packaged to the output directory as a whole. Webpack realizes the modularization of the whole project through such characteristics.

11. Core working principle of Webpack

The Loader mechanism is at the heart of Webpack

Package the core work process

Throughout the project, there are various resource files scattered around, and WebPack will find one of them based on the configuration and use it as an entry point for packaging. This file is normally js file, then down the entry code file, according to the code in the import or the require statement, parsing of a resource required to service this deduce this file depends on module, and then analyzed each resource module corresponding to rely on, finally formed the whole project all the files in dependence on dependency tree, With this depend on the tree, webpack recursive this depend on the tree, and then find each node corresponds to a resource file, finally, in according to the rules in the configuration file attributes, to find the modules of the loader, and then give the corresponding loader to load the module, the final will be loaded into the results into the package, To achieve the packaging of the entire project.

12. Working principle of Webpack Loader

Loader is responsible for converting resource files from input to output. Multiple Loaders can be used to process the same resource, but the loader pipe must return a JS code at the end

Common Webpack plugins

1. Automatically clear directory plug-ins

yarn add clean-webpack-plugin --dev
Copy the code

2. Automatically generate HTML using packaged results

yarn add html-webpack-plugin --dev
Copy the code

3. Copy static resources

yarn add copy-webpack-plugin --dev
Copy the code

Webpack develops a plug-in

Webpack requires that the plug-in be either a function or an object that contains the Apply method. Plug-ins implement extensions by mounting functions in lifecycle hooks

class MyPlugin {
  apply (compiler) {
    console.log('MyPlugin starting')

    compiler.hooks.emit.tap('MyPlugin'.compilation= > {
      // compilation => can be understood as the context of this compilation
      for (const name in compilation.assets) {
        // console.log(name)
        // console.log(compilation.assets[name].source())
        if (name.endsWith('.js')) {
          const contents = compilation.assets[name].source()
          const withoutComments = contents.replace(/\/\*\*+\*\//g.' ')
          compilation.assets[name] = {
            source: () = > withoutComments,
            size: () = > withoutComments.length
          }
        }
      }
    })
  }
}

module.exports = {
  plugins: [
    new CleanWebpackPlugin(),
    // Used to generate index.html
    new HtmlWebpackPlugin({
      title: 'Webpack Plugin Sample'.meta: {
        viewport: 'width=device-width'
      },
      template: './src/index.html'
    }),
    // Used to generate about.html
    new HtmlWebpackPlugin({
      filename: 'about.html'
    }),
    new CopyWebpackPlugin([
      // 'public/**'
      'public'
    ]),
    new MyPlugin()// Create your own plug-in]}Copy the code

15. Webpack compiles automatically

Watch working mode

Listen for file changes and automatically repackage

yarn wabpack --watch // Running webpack like this will be in listening mode
Copy the code

Webpack automatically refreshes the browser

Installing the BrowserSync plugin has many drawbacks

17, Webpack Dev Server

Webpack provides HTTP Server for development, including auto-compile and auto-refresh browser functions. To improve productivity, dev-Server does not write the package results to disk (temporary memory). The internal HTTP Server reads these files directly from memory. Then send it to the browser, which can reduce unnecessary disk reads and writes and greatly improve build efficiency.

yarn add webpack-dev-server --dev
Copy the code

Static resource access

As long as the output files are packaged by Webpack, they can be accessed normally, but if there are static resources that also need to be accessed as development servers to resources, there is an additional need to tell Webpack dev-server. To do this, add a configuration in the WebPack configuration to configure the devServer property.

devServer: {
    contentBase: './public'.//contentBase can be a string or an array
  },
Copy the code

ContentBase can specify additional lookup resource directories for the development server

The proxy API service does not understand

18, Source Map

Used to Map the relationship between Source code and converted code, which can be reversely converted back to Source code using Source Map. It mainly solves the debugging problem caused by the inconsistency between the source code and the running code

19. Webpack configures Source Map

Webpack supports 12 source map styles, which means there are many different implementation methods, each of which has different effects and efficiency, the best, the slowest, the fastest, and the least effect.

The eval mode

The fastest build, the effect is simple, can only locate the name of the source code, not the specific column information

20. Webpack Devtool mode comparison

inline-source-map

hidden-source-map

In this mode, the source map effect is not visible under development tools, which is useful for developing third-party packages.

nosource-source-map

This mode allows you to see the error message, but if you click on it, you can’t see the source code, indicating that you don’t have the source code, but provides column information to protect the source code from others in the production environment.

21. How to select an appropriate Source Map

Development mode

The cheap-module-eval-source-map pattern is commonly used

Production mode

No, because it exposes the source code, and because debugging is done during the development phase, there is no need to use source map during the build phase. If you must use nosource-source-Map, you can use nosource-map.

22. Webpack HMR(Module hot Replacement)

Hot plug

Plug and unplug the device in a running machine at any time, and the state of the machine is not affected by the plug and unplug device, and the plug device can immediately start to work like the USB interface in life

Module hot replacement

The ability to replace a module in real time without changing the running state of an application is one of the most powerful features in Webpack and one of the most popular.

use

HMR integration with webpack-dev-server does not require a separate module installation. It can be enabled by running the webpack-dev-server command followed by –hot, or configured in a configuration file.

Implement hot replacement of all modules

Style files can be directly hot updated, but JS files cannot, because JS file encoding is irregular, so Webpack cannot process the updated module, so it cannot realize the replacement scheme common to all files, so it needs to manually process the hot replacement of JS module after update.

Projects created through scaffolding are internally integrated with the HMR solution, so no manual processing is required.

The HMR in Webpack does not come out of the box and requires some manipulation that requires manual handling of module hot replacement logic,

JS module hot replacement

Image module hot replacement

Personal understanding

When the developer changes the source code, the page is refreshed, and then whatever was edited on the page is lost and written again, but if you want to add new code, the state data is not lost, you use module hot replacement.

Webpack uses the HMR APIs

Js files are implemented through the HMR API to achieve hot replacement of modules, after use will not trigger page updates.

Because each file needs to retain different states, it cannot write the same replacement logic, so the replacement of JS files in different states needs to write different replacement logic

24, Webpack HMR notes

1. Errors in HMR code processing will cause an automatic refresh. Use hotOnly to process HMR code.

2. When HMR is not enabled, an error occurs on the HMR API

If Dev Server uses the HMR API but does not have the HMR option enabled, an error will be reported

25. Webpack environment configuration and optimization

Production environment and development environment has very big difference, production environment pay attention to efficiency, focus on the development of the development environment efficiency, and in the development environment to develop more efficient, we will use many tools such as Source Map and HMR, these tools will add additional code to output, this will let the packaging result more and more bloated. Webpack recommends creating different configurations for different work environments.

Configuration modes in different environments

  1. Export configuration files based on different environments and determine environment names and parameters. This mode is only suitable for small and medium-sized projects

yarn webpack Webpack is packaged in development mode with no arguments
yarn webpack --env production // Pass in the production argument, using the production mode package
Copy the code
  1. One configuration file for each environment is recommended for large projects, in which case there are at least three profiles, two for different environments (development and production) and one for common configuration.

First create webpack.common.js to store the common configuration, webpack.dev.js to store the development environment configuration, and webpack.prod.js to store the production environment configuration

Download WebPack-Merge for merging with common environment configurations

yarn add webpack-merge --dev
Copy the code

Run YARN webpack –config webpack.prod.js to package the production configuration

26. Webpack DefinePlugin

Use to register members globally

27, Webpack Tree shaking

Shaking unreferenced code (dead-code) automatically checks unreferenced code and removes it. Removing redundant code is a very important optimization in production. Tree-shaking is automatically enabled in production.

use

Tree-shaking is not a configuration option in Webpack, it is an optimization for a set of functions that are used together

Webpack integration modules (concatenateModules)

The effect is to merge as many modules as possible into a single function, which increases productivity and reduces code size. This feature is also known asIn the case of Scope promotion,Is a feature added in webpack3minimizeUsing them together makes the code much smaller

29, Webpack Tree- Shaking & Babel

There are many books that say that using tree-shaking causes babel-loader to fail

First of all, the premise of a tree-shaking implementation is that the code must be organized using ESModules, which means that the packaged code given to WebPack must be modular in the ESM way. Before packaging, webPack will send modules to different Loaders according to the configuration, and then package all loader processing results together. In order to convert ESAScript features in the code, babel-Loader will be used for JS processing. It’s possible to get rid of ESModules and make them into CommonJS(depending on whether there’s a plug-in for transforming ESM),

conclusion

The latest version of Babel-Loader does not cause Tree shaking to fail, because babel-Loader automatically turns off the ESM transformation plug-in. If you are really worried, you can turn off the ESM transformation manually in the WebPack configuration.

30, Webpack sideEffects

Allowing us to use configuration to flag code for side effects gives tree-shaking more compression. Side effect: What the module does at execution other than exporting members. Make sure your code has no side effects before using this feature

SideEffects is generally used to flag NPM packages for sideEffects

scenario

You can use sideEffects when you import three packages from one file and use one package from that file, but all three packages will show up in the package. The desired result is to remove the two unused packages. SideEffects is configured in webpack to enable this functionality, and in package to indicate that our code has no sideEffects.

Webpack Code splitting

1. Multiple packaging entry, packaging at the same time, output multiple packaging results, applicable scenarios, multi-page applications, a page corresponds to a packaging entry, the common part of separate extraction

Extract common modules

There must be common modules at different entrances

2. Dynamic import to load modules on demand and save bandwidth and traffic. Dynamically imported modules are automatically subcontracted

32, Webpack magic notes

By default through dynamic import, the generated package file, name is just a serial number, if you need to give the package file name, you can use magic notes

In this way, both files will be packaged into the Components file, so that dynamically loaded files can be flexibly packaged to the desired location.

33, Webpack MiniCssExtractPlugin(Extract CSS to a single file)

The CSS must exceed 150kb to be extracted into a single file

yarn add mini-css-extract-plugin --dev
Copy the code

12, Webpack optimize- CSS – Assets -webpack-plugin

34. Webpack prints the filename Hash

When front-end resource files are deployed, static resource caching is enabled on the server. The user browser does not need to request the server to obtain static resources after caching, which greatly improves the response speed.

Open the client resource cache will bring new problems, if in the caching policy, the timing of the cache invalidation is too long, update in the time of application, after the relocation, there is no way to update to the client, in order to solve this problem, under the mode of production, suggested that the output file name use hash value, once the resource file changes, The file name changes as well, and from the client’s point of view, the new file name is equivalent to a completely new request, which solves the problem.

There are three ways to set the hash file name

Item level hash

chunkhash

Contenthash file-level hash (best for caching)

Generally, the hash value is 20. You can also manually design the number of digits