Webpack5 core principles and application practice (basic usage) one


foreword

Record the basic configuration rules of Webpack; use specific methods, tools and techniques according to the scenario and technology stack.
Mainly include: building a complete JavaScript and CSS development environment; building micro-frontends, NPM packages, desktop applications, etc.


1. Webpack configuration items

1. Webpack compilation process

There are countless Webpak native configuration items, which will eventually act on different stages

The general compilation process can be divided into four processes:

Input— > Module Processing— > Post-processing— > Output

  • Input : read in code files from the filesystem
  • Module recursive processing : Call the Loader to translate the Module (module) content, and convert the result into an AST (Abstract Syntax Tree), analyze the module dependencies from it, and further call the module processing process recursively until all dependent files are processed;
  • Post-processing : After all modules are recursively processed, post-processing starts, including module merging , injecting runtime , product optimization, etc., and finally outputs a collection of Chunk (a collection of modules according to certain rules);
  • Output : write the Chunk to the external file system;

2. Webpack configuration

Webpack configuration items can be divided into two categories

  • Process class : a configuration item that acts on one or several links of the packaging process and directly affects the compilation and packaging effect
  • Tool class : In addition to packaging the main process, it provides more configuration items for engineering tools

(1) Process class configuration

Configurations that are strongly related to process configuration include:

  • input Output:
    • entry: It is used to define project entry files, and Webpack will start from these entry files to find all project files according to the map;
    • context: project execution context path;
    • output: Configure the product output path, name, etc.;
  • Module processing:
    • resolve: Used to configure module path parsing rules, which can be used to help Webpack find specified modules more accurately and efficiently
    • module: Used to configure module loading rules, such as which Loaders need to be used for processing what types of resources
    • externals: Used to declare external resources, Webpack will directly ignore these resources, skip the parsing and packaging operations of these resources
  • Post-processing:
    • optimization: Used to control how to optimize the product package volume, built-in Dead Code Elimination , Scope Hoisting , code obfuscation, code compression and other functions
    • target: It is used to configure the target operating environment of the compiled product. It supports web, node, electron and other values. The final product will be different with different values.
    • mode: Compilation mode phrase, supports development, production and other values, can be understood as a phrase for declaring the environment

Webpack firstentry/context needs to find the project entry file according to the input configuration ( ); then process the module files one by one according to module/resolve/externalsthe rules configured by module processing (etc.), the processing process includes translation, dependency analysis, etc .; Configuration items ( optimization/targetetc.) merge module resources, inject runtime dependencies, optimize product structure, etc.


(2) Tool configuration

In addition to the core packaging functions, Webpack also provides a series of tools for improving R&D efficiency, which can be roughly divided into:

  • Development efficiency class:
    • watch: Used to configure continuous monitoring of file changes and continuous construction
    • devtool: Used to configure the product Sourcemap (storing the corresponding location information before and after code conversion) generation rules
    • devServer: Used to configure development server functions strongly related to HMR (Module Hot Update)
  • Development efficiency class:
    • cache: After Webpack 5, this item is used to control how to cache compilation process information and compilation results
    • performance: Used to configure how to notify the developer when the product size exceeds the threshold
  • Log class:
    • stats: It is used to precisely control the log content of the compilation process, which is very useful when doing more detailed performance debugging
    • infrastructureLogging: Used to control the log output method, for example, the log can be output to a disk file through this configuration

3. Configuration logic

The file structure is as follows:

.
├── src
|   └── index.js
└── webpack.config.js

Among them, src/index.jsis the project entry file, webpack.config.jsand is the Webpack configuration file. In the configuration file, first we need to declare the project entry:

// webpack.config.js
module.exports = {
    
    
  entry: "./src/index"
};

Declare the product output path:

// webpack.config.js
const path = require("path");

module.exports = {
    
    
  entry: "./src/index",
  output: {
    
    
    filename: "[name].js",
    path: path.join(__dirname, "./dist"),
  }
};

In front-end projects, it is often necessary to process resources other than JS, including css, ts, images, etc. At this time, it is necessary to configure appropriate loaders for these resources:

// webpack.config.js
const path = require("path");

module.exports = {
    
    
  entry: "./src/index",
  output: {
    
    
    filename: "[name].js",
    path: path.join(__dirname, "./dist"),
  },
  module: {
    
    
    rules: [{
    
    
      test: /\.less$/i,
      include: {
    
    
        and: [path.join(__dirname, './src/')]
      },
      use: [
        "style-loader",
        "css-loader",
        // "./loader",
        {
    
    
          loader: "less-loader",
        },
      ],
    }],
  },
};

2. Scaffolding tools

For the advancement of the project, configuration management will be very difficult. So the community provides corresponding scaffolding tools to manage configuration.

  • Vue CLI : A command-line tool used to help users quickly create and run Vue.js project scaffolding;
  • create-react-app : A command-line tool for scaffolding React projects;
  • @ angular/cli : a command line tool for creating angular projects;
  • webpack-cli : The command line tool officially provided by Webpack, which provides a set of instruction sets for interactively generating configuration files, as well as functions such as project compilation, development, and migration;
  • Neutrino : A tool for quickly creating and running modern JavaScript applications, and supports React, Preact, Vue, Web, Node.js, Library and other scenarios;
  • react-starter-kit : A scaffolding tool for creating React + Relay + GraphQL applications, with built-in SSR support.

1. Vue CLI build project scaffolding

The bottom layer of Vue CLI calls Webpack to realize the compilation and packaging function for .vue and other resources; calls webpack-dev-server to realize the development server function including HMR function; it can also integrate ESLint , Babal , Less and other tools through plug-ins .

Installation dependencies: (after the installation is complete, you can use vue -V to test whether the installation is successful)

npm install -g @vue/cli

# 或者使用 yarn
yarn global add @vue/cli

Create a project: vue createcommand (you can use vue create --helpthe command to view the parameter list of create 仅限于 vue3中使用)

vue create 项目名

After executing the create command, the CLI will further ask which scaffolding scheme to use:
usually the third custom

Vue CLI v4.5.15
? Please pick a preset: (Use arrow keys)Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint)
  Manually select features

Vue2 uses vue init webpack 项目名to build the project
, basically press Enter, and the last four items are based on your own needs.

 Project name webpack5-dispose
? Project description A Vue.js project
? Author xxx <邮箱>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) yarn

The bottom layer of Vue CLI relies on Webpack to implement engineering capabilities such as compilation and packaging. Developers can modify Webpack configuration information through configureWebpackand configuration items.chainWebpack

// vue.config.js
module.exports = {
    
    
  configureWebpack: {
    
    
    plugins: [
      new MyAwesomeWebpackPlugin()
    ]
  }
}

The configuration rules of configureWebpack are consistent with those of Webpack, and also support configuration items such as plugins/module/resolve. In fact, Vue CLI will eventually call webpack-merge to merge the configureWebpack value with other context configurations to generate the final Webpack configuration information.

// vue.config.js
module.exports = {
    
    
  chainWebpack: config => {
    
    
    config.module
      .rule('vue')
      .use('vue-loader')
        .tap(options => {
    
    
          // modify the options...
          return options
        })
  }
}

Use the inspect command to generate complete Webpack configuration information:

vue inspect > output.js

2. CRA builds project scaffolding

Use the following code to create a react project using CRA. When webStrom creates a react project, CRA can be used to create the project

npx create-react-app [项目名称]

insert image description here


The scaffolding created by the default rules includes the following engineering capabilities:

  • JSX, ES6, TypeScript, Flow syntax support
  • CSS automatically adds the --webkit-- prefix
  • Jest-based automated testing capabilities
  • A development server that supports HMR
  • etc.

If necessary, you can also use npm run ejectthe command to export the complete project configuration structure:
Note: There may be unmanaged files that need to be submitted before using this command
to generate the corresponding configuration:

insert image description here

After exporting the configuration, you can directly modify webpack.config.jsrelated configuration files to control the behavior of various functions.


3. How to build a modern JS engineering environment with Babel+TS+ESLint

1. Use Babel

Function: Used to make the code backward compatible and run in the old version of the JS engine
Because ES6 provides many new JS features, this will cause compatibility problems with the old version of JS and Node , etc. Babel is to solve this problem, it will Translate the code to the old version of the code, so that the old version of the engine can be used normally.

// 使用 Babel 转译前
arr.map(item => item + 1)

// 转译后
arr.map(function (item){
    
    
  return item + 1;
})

In the Webpack scenario, you only need to use babel-loaderto access the Babel translation function:

  1. install dependencies
npm i -D @babel/core @babel/preset-env babel-loader
  1. Add module processing rules
module.exports = {
    
    
  /* ... */
  module: {
    
    
    rules: [
      {
    
    
        test: /\.js$/, // 规则 表示所有.js后缀文件
        use: ['babel-loader'], // 使用babel-loader处理
      },
    ],
  },
};
  1. Execute the compile command
npx webpack
  1. Babel feature logic can be configured using the .babelrc file or the rule.options property
// 预先安装 @babel/preset-env
// npm i -D @babel/preset-env
module.exports = {
    
    
  /* ... */
  module: {
    
    
    rules: [
      {
    
    
        test: /\.js$/,
        use: [
          {
    
    
            loader: 'babel-loader',
            options: {
    
    
              presets: ['@babel/preset-env'],
            },
          },
        ],
      },
    ],
  },
};

@babel/preset-env is the Babel preset rule set - Preset, which can use various Preset resources:

  • babel-preset-react: Contains the rule set of commonly used React plugins, supports preset-flow, syntax-jsx, , transform-react-jsxetc.;
  • @babel/preset-typescript: A ruleset for transpiling TypeScript code
  • @babel/preset-flow: Ruleset for translating Flow code

view-cli

In the file, build/webpack.base.conf.jsthe scaffolding has been configured with 相关的配置项,但我们依然可以在the webpack.config.js 中修改一些配置 entry `entry file

entry: {
    
    
    app: './src/main.js'
  },

outputThe target location of the compiled product

output: {
    
    
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'// 判断是什么环境
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },

resolveparsing rules

  resolve: {
    
    
    extensions: ['.js', '.vue', '.json'],//文件扩展名
    alias: {
    
    // 别名
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },

modeleparsing module

 module: {
    
    
    rules: [
      {
    
    
        test: /\.vue$/, // 规则过滤条件,这里表示对所有 .vue 后缀文件
        loader: 'vue-loader',// vue-loader处理
        options: vueLoaderConfig
      },
      {
    
    
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
    
    
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
    
    
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
    
    
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
    
    
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
    
    
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
    
    
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },

CRA

config/webpack.config.jsThere is already some scaffolding for my door configuration in

module: {
    
    
    rules: [
      {
    
    
        test: /\.js$/,// 声明该规则过滤文件,只有路径和文件类型对应才会生效,此处为所有的 .js 后缀的文件生效
        loader: 'babel-loader',// 所有命中文件传入Loader序列做转译
        include: [resolve('src'), resolve('test'), //包内容路径 这里时src和test下的文件  
        resolve('node_modules/webpack-dev-server/client')]// 以及node_modules中自己的包
      }
    ]
  }

Not only the files in the program are configured, but also the files outside the file are configured.

{
    
    
              test: /\.(js|mjs)$/,
              exclude: /@babel(?:\/|\\{1,2})runtime/,
              loader: require.resolve('babel-loader'),
              options: {
    
    
                babelrc: false,
                configFile: false,
                compact: false,
                presets: [
                  [
                    require.resolve('babel-preset-react-app/dependencies'),
                    {
    
     helpers: true },
                  ],
                ],
                cacheDirectory: true,
                // See #6846 for context on why cacheCompression is disabled
                cacheCompression: false,
                
                // Babel sourcemaps are needed for debugging into node_modules
                // code.  Without the options below, debuggers like VSCode
                // show incorrect code and set breakpoints on the wrong lines.
                sourceMaps: shouldUseSourceMap,
                inputSourceMap: shouldUseSourceMap,
              },
            },

2. Use TypeScript

Role: Provides a series of type constraints, which can detect errors earlier and ensure type safety in the running phase, suitable for use in multi-person collaborative projects.

Webpack has many ways to access TypeScript, including ts-loader, awesome-ts-loader, babel-loader. Typically TypeScript code can be ts-loaderbuilt using:

Both Vue CLi and CRA use babel-loaderimport TypeScript

  1. install dependencies
npm i -D @babel/preset-typescript
  1. Configure Webpack
// 预先安装 @babel/preset-env
// npm i -D @babel/preset-env
module.exports = {
    
    
  /* ... */
  module: {
    
    
    rules: [
      {
    
    
        test: /\.js$/,
        use: [
          {
    
    
            loader: 'babel-loader',
            options: {
    
    
              presets: ['@babel/preset-typescript'],
            },
          },
        ],
      },
    ],
  },
};

@babel/preset-typescriptJust did a simple code conversion, no type checking, etc., you can use other Preset


3. Use ESLint

As a flexible and weakly typed scripting language, js may cause errors that affect the stability of some syntax and types generated during the development process, which will affect development efficiency and quality. ESLint is to solve these problems .

Function: JS code style checker, which can repair the code that violates the rules.

Under Webpack, you can use eslint-webpack-pluginto access the ESLint tool, steps:

  1. install dependencies
# 安装 webpack 依赖
yarn add -D webpack webpack-cli

# 安装 eslint 
yarn add -D eslint eslint-webpack-plugin

# 简单起见,这里直接使用 standard 规范
yarn add -D eslint-config-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
  1. Add eslintrca .configuration file in the project root directory, content:
// .eslintrc
{
    
    
  "extends": "standard"
}
  1. Add webpack.config.jsa configuration file to supplement eslint-webpack-pluginthe configuration:
// webpack.config.js
const path = require('path')
const ESLintPlugin = require('eslint-webpack-plugin')

module.exports = {
    
    
  entry: './src/index',
  mode: 'development',
  devtool: false,
  output: {
    
    
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  },
  // 添加 eslint-webpack-plugin 插件实例
  plugins: [new ESLintPlugin()]
}
  1. Execute the compile command
npx webpack

You can also use third-party extensions for special code style detection

  • eslint-config-airbnb: The code style rule set provided by Airbnb can be regarded as the first famous rule set in the ESLint ecosystem
  • eslint-config-standard: Standard.js code style rule set, the most convenient way to unify code style in history
  • eslint-plugin-vue: Implement code style checking for Vue SFC files
  • eslint-plugin-react: Implement React code style check
  • @typescript-eslint/eslint-plugin: Implement TypeScript code style checking
  • eslint-plugin-sonarjs: A Sonar-based code quality inspection tool that provides detection functions such as cyclomatic complexity and code repetition rate

Summarize

This article mainly records the underlying logical structure of Webpack configuration and how to build a JS environment with the help of Babel, TS, and ESLint

Guess you like

Origin blog.csdn.net/smznbhh/article/details/127054404