【node】webpack-chain常用配置

介绍

webpack-chain 通过提供可链式的 API 创建和修改 webpack 配置。在 vue-cli 中已采用 webpack-chain 方式修改 webpack 配置。

webpack-chain 文档:https://github.com/neutrinojs/webpack-chain

webpack 文档:https://webpack.js.org/

安装引用

1
npm install -D webpack-chain
1
2
3
const Config = require("webpack-chain");

const config = new Config();

常用配置语法

入口、出口配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
config
// entry 入口配置
.entry("index")
.add("src/index.js")
.end()
// output 出口配置
.output.path("dist")
.filename("[name].[chunkhash].js")
.chunkFilename("chunks/[name].[chunkhash].js");

// 等同于以下 webpack 配置
module.exports = {
entry: {
index: ["src/index.js"],
},
output: {
path: "/dist",
filename: "[name].[chunkhash].js",
},
};

loader 新增

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
config.module
.rule("babel")
.test(/\.(js|jsx|mjs|ts|tsx)$/)
.use("babel-loader")
.loader("babel-loader")
.options({
presets: ["@babel/preset-env"],
})
.end();

// 等同于以下 webpack 配置
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
};

loader 修改

1
2
3
4
5
6
7
8
config.module
.rule("babel")
.use("babel-loader")
.tap((options) => {
// 修改 options...
options.presets = ["@babel/preset-env"];
return options;
});

plugin 新增

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const pluginName = require("plugin-name");

config.plugin("plugin-name").use(pluginName, [
{
// 插件配置项
},
]);

// 等同于以下 webpack 配置
module.exports = {
plugins: [
new pluginName({
// 插件配置项
}),
],
};

plugin 修改

1
2
3
4
5
config.plugin("plugin-name").tap((args) => [
{
// 插件配置args修改
},
]);