Detailed summary of the configuration and use of Webpack5

Packaging tools

Code developed using frameworks (React, Vue), ES6 modular syntax, Less/Sass and other CSS preprocessors and other syntaxes must be compiled into JS, CSS and other syntaxes that the browser can recognize before they can be run. .
So we need packaging tools to help us do these things. In addition, packaging tools can also compress code, perform compatibility processing, improve code performance, etc.

What packaging tools are there?
Grunt, Gulp, Parcel, Webpack , Rollup, Vite

What is webpack

Webpack is a front-end static resource packaging tool. From the perspective of webpack, all resource files on the front end (js/json/css/img/less/…) will be processed as modules. Using one or more files as the entry point for packaging, we compile and combine all the files in our entire project into one or more files and output them. The output file is the compiled file and can be run in the browser section. It will perform static analysis based on the dependencies of the module, and package and generate the corresponding static resources (bundle).
Insert image description here
Webpack itself has limited functions:
Development mode: can only compile ES Module syntax in JS
Production mode: can compile ES Module syntax in JS, and can also compress JS code

Five core concepts of webpack

1.
Entry (Entry) instructs webpack to use which file as the entry starting point to start packaging, analyze and build the internal dependency graph.
2.Output
output (Output) instructs webpack where to output the resource bundles packaged and how to name them.
3. Loader
Loader allows webpack to process non-JavaScript files (webpack itself only understands JavaScript).
4.PluginsPlugins
can be used to perform a wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.
5. Mode
mode (Mode) instructs webpack to use the configuration of the corresponding mode.
Insert image description here

Basic use of webpack

npm init -yInitialize a package description file. After running, package.json will be generated
. Enable Webpack (development mode): npx webpack ./src/main.js --mode=development, and every time you write the configuration file, you will directly npx webpack
set the success mark:
Insert image description here
By default, Webpack will package and output the file to the dist directory.

webpack basic configuration

Create a new configuration file in the project root directory: webpack.config.js

// Node.js的核心模块,专门用来处理文件路径
const path = require("path");

module.exports = {
    
    
  // 入口
  // 相对路径和绝对路径都行
  entry: "./src/main.js",
  // 输出
  output: {
    
    
    // path: 文件输出目录,必须是绝对路径
    // path.resolve()方法返回一个绝对路径
    // __dirname 当前文件的文件夹绝对路径
    path: path.resolve(__dirname, "dist"),
    // 入口文件输出路径
    filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
    // clean: true, // 自动将上次打包目录资源清空
  },
  // 加载器
  module: {
    
    
    rules: [],
  },
  // 插件
  plugins: [],
  // 模式
  mode: "development", // 开发模式
};

Webpack runs based on Node.js, so it adopts the Common.js modular specification

Handling style resources

Webpack itself cannot recognize style resources (Css, Less, Sass, Scss, Styl), so we need to use Loader to help Webpack parse style resources.

Handle CSS resources

Two loaders need to be downloaded: npm i css-loader style-loader -D
css-loader: Responsible for compiling CSS files into modules that Webpack can recognize
style-loader: It will dynamically create a Style tag, which contains the CSS module content in Webpack.
Usage: Add to the rules in webpack.config.js:

rules: [
  {
    
    
    // 用来匹配 .css 结尾的文件
    test: /\.css$/,
    // use 数组里面 Loader 执行顺序是从右到左
    use: ["style-loader", "css-loader"],
  },
],

src/css/index.css:

.box1 {
    
    
  width: 100px;
  height: 100px;
  background-color: red;
}

src/main.js:

import count from "./js/count";
// 引入 Css 资源,Webpack才会对其打包
import "./css/index.css";

console.log(count(2, 1));

public/index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>webpack5</title>
  </head>
  <body>
    <h1>Hello Webpack5</h1>
    <!-- 准备一个使用样式的 DOM 容器 -->
    <div class="box1"></div>
    <!-- 引入打包后的js文件,才能看到效果 -->
    <script src="../dist/static/js/main.js"></script>
  </body>
</html>

Run the command: npx webpack, open the index.html page to see the effect.

The same principle applies to other (Less, Sass, Scss, Styl), just follow the official website configuration.

Process image resources

Webpack4 processes image resources through file-loader and url-loader. Now Webpack5 has built the two Loader functions into Webpack. It only requires simple configuration to process image resources.

Usage: Add to the rules in webpack.config.js:

{
    
    
  test: /\.(png|jpe?g|gif|webp)$/,
  type: "asset",
  parser: {
    
    //对图片资源进行优化
    dataUrlCondition: {
    
    
      maxSize: 10 * 1024 // 小于10kb的图片会被base64处理
    }
  },
  generator: {
    
    //修改输出资源的名称和路径
    // 将图片文件输出到 static/imgs 目录中
    // 将图片文件命名 [hash:8][ext][query]
    // [hash:8]: hash值取8位
    // [ext]: 使用之前的文件扩展名
    // [query]: 添加之前的query参数
    filename: "static/imgs/[hash:8][ext][query]",
  },
},

Optimize image resources: Convert images smaller than a certain size into data URI format (Base64 format, advantages: reduce the number of requests; disadvantages: larger size), the images are built into js in the form of data URI, no Output to dist. (Note: You need to clear the files generated by the last packaging and then repackage to have the effect )

Webpack will output all packaged image resources to the dist directory. The style resources are processed by style-loader and packaged into main.js, so there is no additional output.

type: "asset/resource" is equivalent to file-loader, which converts files into resources that Webpack can recognize, and does not process the rest;
type: "asset" is equivalent to url-loader, which converts files into resources that Webpack can recognize, and at the same time Resources smaller than a certain size will be processed into data URI form.

Process js resources

Webpack's processing of js is limited. It can only compile the ES modular syntax in js and cannot compile other syntax. As a result, js cannot run in browsers such as IE, so some compatibility processing must be done. Secondly, during development, the team has strict requirements on code format and needs to use professional tools to detect it. For js compatibility processing, use Babel; for code format, use Eslint.

Eslint

A tool used to detect js and jsx syntax. Write various rules in the Eslint configuration file. When running Eslint in the future, the code will be checked based on the written rules.
1. Download package:npm i eslint-webpack-plugin eslint -D

2. Define the Eslint configuration file .eslintrc.js:

module.exports = {
    
    
  // 继承 Eslint 规则
  extends: ["eslint:recommended"],
  env: {
    
    
    node: true, // 启用node中全局变量
    browser: true, // 启用浏览器中全局变量
  },
  parserOptions: {
    
    // 解析选项
    ecmaVersion: 6, // ES 语法版本
    sourceType: "module", // ES 模块化
    ecmaFeatures: {
    
     // ES 其他特性
      jsx: true // 如果是 React 项目,就需要开启 jsx 语法
  	}
  },
  rules: {
    
    
    "no-var": 2, // 不能使用 var 定义变量
  },
};

rules Specific rules:
"off" or 0 - turn off the rule
"warn" or 1 - turn on the rule, use warning level errors: warn (will not cause the program to exit)
"error" or 2 - turn on the rule, use error level errors: error (when triggered, the program will exit)

extends inheritance: It is too laborious to write rules bit by bit during development, so there is a better way to inherit the existing rules:
Eslint official rules: eslint:recommended
Vue Cli official rules: plugin:vue/essential
React Cli official Rules: react-app

3. Modify main.js

4. Configure webpack.config.js:

const ESLintWebpackPlugin = require("eslint-webpack-plugin");
……
plugins: [
  new ESLintWebpackPlugin({
    
    
    // 指定检查文件的根目录
    context: path.resolve(__dirname, "src"),
  }),
],

5. Run the command:npx webpack

VSCode has an Eslint plug-in, so you can see errors without compiling. At this time, all files in the project will be checked by Eslint by default, and errors will be reported for packaged files in the dist directory.
So you only need to check the files under src, and there is no need to check the files under dist. Use Eslint to ignore the files. Create the following files in the project root directory .eslintignore:

# 忽略dist目录下所有文件
dist

Babel

JavaScript compiler, mainly used to convert code written in ES6 syntax into backward-compatible JavaScript syntax so that it can run in current and older versions of browsers or other environments.
1. Download package:npm i babel-loader @babel/core @babel/preset-env -D

2. Define the Babel configuration file babel.config.js:

module.exports = {
    
    
  presets: ["@babel/preset-env"],
};

presets: It is a set of Babel plug-ins that extend Babel functions.
@babel/preset-env: A smart preset that allows using the latest JavaScript.
@babel/preset-react: A preset for compiling React jsx syntax.
@babel/preset-typescript: A preset for compiling TypeScript syntax.

3. Modify main.js

4. Configure webpack.config.js:
Add: in rules:

{
    
    
  test: /\.js$/,
  exclude: /node_modules/, // 排除node_modules代码不编译
  loader: "babel-loader",
},

5. Run the command:npx webpack

Handle Html resources

1. Download the package: npm i html-webpack-plugin -D
2. Configure webpack.config.js:

const HtmlWebpackPlugin = require("html-webpack-plugin");
……
plugins: [
  new HtmlWebpackPlugin({
    
    
    // 以 public/index.html 为模板创建文件
    // 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
    template: path.resolve(__dirname, "public/index.html"),
  }),
],

3. Modify index.html: Remove the imported js file, because HtmlWebpackPlugin will automatically introduce it.
4. Run the command:npx webpack

automation

Every time you finish writing code, you need to manually enter instructions to compile the code. This is too troublesome. Let's use the development server to automate it.
1. Download the package: npm i webpack-dev-server -D
2. Configure webpack.config.js:

module.exports = {
    
    
  // 添加开发服务器
  devServer: {
    
    
    host: "localhost", // 启动服务器域名
    port: "3000", // 启动服务器端口号
    open: true, // 是否自动打开浏览器
  },
};

3. Run the command: npx webpack serve
Note: When using the development server, all code will be compiled and packaged in memory and will not be output to the dist directory. When developing, you only care about whether the code can run and be effective. You don't need to know what the code is compiled into.

production mode

The production mode is that after the code is developed, we need to get the code and deploy it online in the future. This mode mainly optimizes code running performance and code packaging speed. The original webpack.config.js becomes two.
File Directory:

├── webpack-test (项目根目录)
    ├── config (Webpack配置文件目录)
    │    ├── webpack.dev.js(开发模式配置文件)
    │    └── webpack.prod.js(生产模式配置文件)
    ├── node_modules (下载包存放目录)
    ├── src (项目源码目录,除了html其他都在src里面)
    │    └── 略
    ├── public (项目html文件)
    │    └── index.html
    ├── .eslintrc.js(Eslint配置文件)
    ├── babel.config.js(Babel配置文件)
    └── package.json (包的依赖管理配置文件)

The file directory has changed, so all relative paths need to go back one directory to find the corresponding files, and webpack.dev.js needs to be modified:

path: undefined, // 开发模式没有输出,不需要指定输出目录
// clean: true, // 开发模式没有输出,不需要清空输出结果
context: path.resolve(__dirname, "../src"),
template: path.resolve(__dirname, "../public/index.html"),

Instructions to run development mode:npx webpack serve --config ./config/webpack.dev.js

Modify webpack.prod.js:

path: path.resolve(__dirname, "../dist"), // 生产模式需要输出
mode: "production",

Instructions to run production mode:npx webpack --config ./config/webpack.prod.js

Configure quick run instructions

In order to facilitate running instructions in different modes, define the instructions in scripts in package.json:

// package.json
{
    
    
  // 其他省略
  "scripts": {
    
    
    "start": "npm run dev",
    "dev": "npx webpack serve --config ./config/webpack.dev.js",
    "build": "npx webpack --config ./config/webpack.prod.js"
  }
}

Later startup instructions: (start does not need to be added with run, others need to be added)
Development mode: npm startor npm run dev
production mode:npm run build

Handle CSS separately

The CSS file is currently packaged into a js file. When the js file is loaded, a style tag will be created to generate the style. In this way, for the website, there will be a splash screen phenomenon and the user experience is not good. It should be a separate CSS file, through Link tag loading performance is better.
1. Download the package: npm i mini-css-extract-plugin -D
2. Configure webpack.prod.js:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
rules: [
  {
    
    
    test: /\.css$/,
    // 将先前的"style-loader"替换成MiniCssExtractPlugin.loader
    use: [MiniCssExtractPlugin.loader, "css-loader"],
  },
],
plugins: [
  // 提取css成单独文件
  new MiniCssExtractPlugin({
    
    
    // 定义输出文件名和目录
    filename: "static/css/main.css",
  }),
],

3. Run the command:npm run build

CSS compatibility handling

1. Download the package: npm i postcss-loader postcss postcss-preset-env -D
2. Configure webpack.prod.js:

rules:[
  {
    
    
    test: /\.less$/,
    use: [
      MiniCssExtractPlugin.loader,
      "css-loader",
      {
    
    
        loader: "postcss-loader",
        options: {
    
    
          postcssOptions: {
    
    
            plugins: [
              "postcss-preset-env", // 能解决大多数样式兼容性问题
            ],
          },
        },
      },
      "less-loader",
    ],
  },
]

When there are too many configurations, the above compatibility processing will be slightly redundant, so it can be abstracted into a function to merge the configurations:

// 获取处理样式的Loaders
const getStyleLoaders = (preProcessor) => {
    
    
  return [
    MiniCssExtractPlugin.loader,
    "css-loader",
    {
    
    
      loader: "postcss-loader",
      options: {
    
    
        postcssOptions: {
    
    
          plugins: [
            "postcss-preset-env", // 能解决大多数样式兼容性问题
          ],
        },
      },
    },
    preProcessor,
  ].filter(Boolean);
};
……

rules:[
  {
    
    
   // 用来匹配 .css 结尾的文件
    test: /\.css$/,
    // use 数组里面 Loader 执行顺序是从右到左
    use: getStyleLoaders(),
  },
  {
    
    
    test: /\.less$/,
    use: getStyleLoaders("less-loader"),
  },
  {
    
    
    test: /\.s[ac]ss$/,
    use: getStyleLoaders("sass-loader"),
  },
]

3. Control compatibility: You can add browserslist in the package.json file to control the extent of style compatibility.

{
    
    
  // 其他省略
  "browserslist": ["last 2 version", "> 1%", "not dead"]
}

3. Run the command:npm run build

CSS compression

1. Download the package: npm i css-minimizer-webpack-plugin -D
2. Configure webpack.prod.js:

const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
plugins: [
  // css压缩
    new CssMinimizerPlugin(),
],

3. Run the command:npm run build

The default production mode is already enabled: html compression and js compression, no additional configuration is required.

Reference documentation

Guess you like

Origin blog.csdn.net/zag666/article/details/123161975