webpack是一个现代JS应用的一个模块打包器,作用为将所有资源(JS,css,图片等)打包为多个静态文件。

配置文件

​ 写在webpack.config.js中,格式为:

1
2
3
4
// webpack.config.js
module.exports = {
// …
};

Entry(入口) Output(出口)

​ 入口文件与出口文件

1
2
3
4
5
6
7
8
9
10
11
12
13
// webpack.config.js
const path = require('path')
module.exports = {
// 入口文件
entry: './src/index.js', // 入口文件路径
// 出口文件
output: {
filename: 'main.js', // 出口文件名
path: path.resolve(__dirname, 'dist'), // 出口文件路径,必须绝对路径
clean: true, // 每次构建是否清除path目录
},
};

Mode(模式)

​ 用于设置编译模式,可选 “production”,”development”,”none”

  • production:生产模式,开启代码压缩,如:删除未用到的代码;
  • development:开发模式,保留注释,不压缩代码。

Loaders(加载器)

​ 原生webpack只能打包JS与JSON代码,因此要打包其他资源需要对应的Loader(或资源模块Asset Moudules)。

​ 如要解析css文件就需要style-loader与css-loader:

1
2
3
4
5
6
7
8
9
10
11
12
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i, // 指定哪些文件需要被处理,形式为正则表达式
use: ['style-loader', 'css-loader'], // 使用哪些loader进行处理,执行顺序为从后往前执行
// css-loader只负责将css文件转为js,style-loader处理css文件并插入到html中
},
]
},
}

Plugins(插件)

​ 不对代码进行处理,但会拓展一些功能,在生命周期中注入或修改行为。

​ 如使用HtmlWebpackPlugin插件在构建时根据模版生成html并自动注入打包资源:

  1. 安装

    1
    npm install --save-dev html-webpack-plugin
  2. 在配置中引入并实例化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // webpack.config.js
    // 引入html-webpack-plugin插件
    const HTMLPlugin = require('html-webpack-plugin')
    module.exports = {
    plugins: [
    new HTMLPlugin({
    title: 'test', // 配置生成html文件的标题
    template: './src/index.html' // 配置生成html文件的模板
    filename: 'index.html', // 配置生成html文件的名称
    inject: 'body', // 配置html文件插入的位置,放在</body>前
    minify: true // 配置html文件的压缩,打包时压缩html
    })
    ]
    }

    Asset Modules(资源模块)

    Asset Modules 是从 Webpack 5 开始引入的一种 新的资源模块类型,用于代替旧版中通过 file-loaderurl-loaderraw-loader 等处理静态资源的方式。让我们在不额外安装loader的情况下即可处理一些静态资源。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // webpack.config.js
    module.exports = {
    // ...
    module: {
    rules: [
    {
    test: /\.(jpg,png)$/i,
    type: 'asset/resource',
    }
    ]
    },
    }

    Devtool*

    ​ 用来控制如何生成**Source Map(源码映射)**,安装source-map,使源码在浏览器的源代码中可见并可调试。

    ​ 不同的devtool模式,其构建速度、打包体积和映射精度各不相同。

    1
    2
    3
    4
    5
    6
    // webpack.config.js
    const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
    module.exports = {
    // ...
    devtool: "inline-source-map",
    }