Webpack Basics

Time:2021-9-10

brief introduction

In essence,webpackIs an example of a modern JavaScript applicationStatic module packaging tool。 When a webpack processes an application, it builds one internallyDependency graph, this dependency graph maps each module required by the project and generates one or morebundle

webpackIt is a tool for packaging modular JavaScript. It will start from the entry module, identify the modular import statements in the source code, recursively find out all the dependencies of the entry file, and package the entry and all its dependencies into a separate file

It is the embodiment of engineering and automation in front-end development.

Webpack 5. X was launched during the National Day on October 1 last year, but considering the instability and the update of ecological plug-ins, the sharing is still dominated by webpack 4. X. ([email protected][email protected])

Webpack4. X documentation

Webpack5. X document

Webpack installation

Environmental preparation

nodeJs

The version refers to the latest version released on the official website, which can improve the packaging speed of webpack

Installation mode

  1. Local installation (recommended)

    #When installing the version of webpack V4 +, you need to install an additional webpack cli 
    npm install [email protected] [email protected] -D
  1. Global installation (not recommended)

    npm install [email protected] [email protected] -g

Install webpack globally, which will lock the webpack in your project to the specified version, resulting in conflicts and construction failure of different projects because webpack depends on different versions

Configure core concepts

  • chunk: refers to a code block. A chunk may be composed of multiple modules. It is also used for code merging and segmentation.
  • bundle: the final output result file of the resource after being parsed and compiled by the webpack process.
  • entry: as the name suggests, it is the entry starting point, which is used to tell webpack which file to use as the starting point for building dependency graph. Webpack will recursively find dependencies according to the entry, and each dependency will be processed by it and finally output to the packaging results.
  • output: describes the output configuration of webpack packaging, including the naming and location of output files.
  • loader: by default, webpack only supports. JS. JSON files. Through the loader, it can parse other types of files and act as the “color” of the translator. Theoretically, any type of file can be processed as long as there is a corresponding loader.
  • plugin: the main responsibility of loader is to let webpack know more file types, while the responsibility of plugin is to let it control the construction process to perform some special tasks. The plug-in is very powerful and can complete a variety of tasks.
  • mode: starting from 4.0, webpack supports zero configuration to reduce the difficulty for developers. At the same time, the concept of mode is added to specify the packaging target environment, so as to enable the built-in optimization of webpack for different environments during the packaging process

Small trial ox knife

Zero configuration Version (4. X gimmick)

  • Create a front-end engineering project

    #New project folder
    mkdir wpdemo
    cd wbpdemo
    #Project initialization
    npm init -y
    #Installing webpack dependencies
    npm install [email protected] [email protected] -D
    mkdir src
    touch index.js
    vim index.js
  • Execute package command

    npx webpack

You will find an extra dist directory in the directory, which contains a main.js. This file is an executable JavaScript file that contains the webpackbootstrap startup function.

Configuration version

Webpack has a default configuration file,webpack.config.js, we can modify this file for personalized configuration
Do not use custom profiles: for examplewebpackconfig.js, you can--config webpack.config.js To specify which configuration file webpack uses to perform the build

// webpack.config.js
module.exports = {
  //Package entry file 
  entry: "./src/index.js", 
  output: {
    //Name of the output file
    filename: "bundle.js",
    //The directory from the output file to the disk must be an absolute path
    path: path.resolve(__dirname, "dist")
  },
  Mode: "production", // packaging environment
  module: {
    rules: [ 
        {
          test: /\.css$/,
          //CSS loader analyzes the relationship between CSS modules and synthesizes a CSS
          //Style loader will mount the content generated by CSS loader to the header part of the ⻚ face in style
          use: ["style-loader", "css-loader" ]
        }
     ] },
  //Plug in configuration
  plugins: [new HtmlWebpackPlugin()] 
};
  • entry:

    https://v4.webpack.docschina….

    Specify the webpack package entry file. The first step of webpack execution will start from entry, which can be abstracted into input

    //Single entry spa is essentially a string 
    entry:{
       main: './src/index.js' 
    }
    //Equivalent to entry: ". / SRC / index. JS"
    //Multiple entry is an object 
    entry:{
      index:"./src/index.js",
      login:"./src/login.js" 
    }
  • output:

    https://v4.webpack.docschina….

    Package the converted file and output it to the disk location: output the result. After a series of processing in webpack and obtaining the final desired code, output the result.

    output: {
      //Name of the output file
      filename: "bundle.js",
      //The directory from the output file to the disk must be an absolute path
      path: path.resolve(__dirname, "dist")
    },
    //Multi entry processing 
    output: {
      //Use placeholders and do not duplicate file names
      filename: "[name][chunkhash:8].js",
      //The directory from the output file to the disk must be an absolute path 
      path: path.resolve(__dirname, "dist")
    },
  • mode

    https://v4.webpack.docschina….

    Mode is used to specify the current construction environment (production | development | none). Setting mode can automatically trigger the built-in functions of webpack to achieve the effect of optimization

    • The opening of the development phase will facilitate the processing of hot update and identify which module has changed
    • The opening of the production phase will help module compression, deal with side effects and other functions
  • moudle

    https://v4.webpack.docschina….

    Module. In webpack, everything is a module. A module corresponds to a file. Webpack will recursively find all dependent modules from the configured entry.

    When an unknown module is processed by the webpack, it needs to be configured at the module in the webpack. When a module of what format is detected, what loader is used to process it.

    module:{
      rules:[
        {
          //Specify matching rules 
          test:/\.xxx$/, 
          use:{
            //Specify the loader to use
            loader: 'xxx-load'
          }
        }
        ] 
    }
  • loader

    https://v4.webpack.docschina….

    Module analysis and module converter are used to convert the original content of the module into new content as required. Webpack is a module packaging tool, not just JS, but also CSS, pictures or other formats

    But webpack only knows how to handle it by defaultjsandJSONModule, then the module processing and processing methods of other formats need loader

    Usual loader:

    style-loader
    css-loader
    less-loader
    sass-loader
    TS loader // convert ts to JS Babel loader // convert ES6, 7 and other JS new feature syntax file loader // process the picture subgraph eslint loader
  • plugins

    https://v4.webpack.docschina….

    The plugin can help you do some things when the webpack runs to a certain stage. It is similar to the concept extension plug-in of the life cycle. It injects extension logic at a specific time in the webpack construction process to change the construction results or do what you want. Act on the whole construction process

    Common plugins

    HTML webpack plugin // an HTML file will be automatically generated after packaging, and the JS module generated by packaging will be introduced into the HTML.
    Clean webpack plugin // delete the package file

    For more third-party plug-ins, please seeawesome-webpacklist