@Dale-Lin
2022-08-03T21:37:33.000000Z
字数 1669
阅读 312
webpack5
webpack-merge 提供了一个合并数组/对象的 merge
函数,如果数组/对象的合并过程中遇到了函数,那么会先执行这个函数得到结果,再用一个函数包裹这个执行结果。
merge
是最常用的 API,提供了拆分 webpack 配置的工具:
// webpack.base.js
const path = require('path')
module.exports = {
output: {
path: path.join(__dirname, "./dist"),
},
resolve: {
extensions: [".jsx", ".js"]
},
module: {
rules: [
{
test: /\.jsx$/,
loader: "babel-loader",
options: {
presets: ["@babel/preset-react"]
}
}
]
}
}
// webpack.client.js
const Merge = require("webpack-merge")
const path = require("path")
const HTMLWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const { WebpackManifestPlugin } = require("webpack-manifest-plugin")
const base = require("./webpack.base")
module.exports = Merge.merge(base, {
entry: {
// 入口指向 entry-client.js
client: path.join(__dirname, "./src/entry-client.js")
},
output: {
filename: 'public/index.js',
publicPath: "public/"
},
module: {
rules: [{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}]
},
plugins: [
// 使用 webpack-manifest-plugin 记录产物清单
// 方便在 `serve.js` 中使用
new WebpackManifestPlugin({
fileName: "manifest-client.json"
}),
new MiniCssExtractPlugin({
filename: 'public/index.[contenthash].css'
}),
new HTMLWebpackPlugin({
template: 'public/index.html'
})
]
})
unique
是在配置中强制唯一性的策略,在 plugin 合并时有用:
configField
表示配置项的属性;
uniqueField
表示查找的重复项;
uniqueField => uniqueField
表示判断重复项时应该唯一的值
const { mergeWithCustomize, unique } = require("webpack-merge")
const output = mergeWithCustomize({
customizeArray: unique(
"plugins",
["HotModuleReplacementPlugin"],
(p) => p.constructor && p.constructor.name
)
})(
{
plugins: [new webpack.HotModuleReplacementPlugin()],
},
{
plugins: [new webpack.HotModuleReplacementPlugin()]
}
)