浮声新志

webpack插件篇:NormalModuleReplacementPlugin详解

用途说明

NormalModuleReplacementPlugin (正常模块替换插件)

Replace resources that matches resourceRegExp with newResource. If newResource is relative, it is resolve relative to the previous resource. If newResource is a function, it is expected to overwrite the ‘request’ attribute of the supplied object.

webpack.config.js配置

1
new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource)

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './test.js',
resolve: {
extensions: ['.js']
},
output: {
path: __dirname,
filename: 'test.bundle.js'
},
plugins: [
new webpack.NormalModuleReplacementPlugin(
new RegExp(`^${path.resolve('./string.js')}$`),
function(result) {
result.request = path.resolve('./string-replacement.js');
}
)
]
};