Webpack 打包过程全局替换插件
npm i --save global-replace-plugin
- regExp 匹配全局所需要替换内容的一个正则表达式
- text 替换为指定的内容
//webpack.config.js
var GlobalReplacePlugin = require('global-replace-plugin');
var config = {
...
plugins: [
new GlobalReplacePlugin({
regExp: /\/\/123456789/,
text: 'test()'
})
]
...
};
module.exports = config;
//index.js
const test = () => {
console.log(123456789)
}
//123456789
//打包之后//123456789将被替换为test()
//运行时test函数将会被调用,控制台会打印出123456789
功能叙述:埋点上报逻辑与现有逻辑解耦 正则表达式
//webpack.config.js
var GlobalReplacePlugin = require('global-replace-plugin');
var config = {
...
plugins: [
new GlobalReplacePlugin({
regExp: /\/\/>>>(\w+),(\w+)/g,
//加`号,打包之后$1的值作为字符串处理,不加`号,打包之后$1的值将作为变量处理,那么须提前申明该变量
//不明白$1,$2可点击上方正则表达式
text: 'report(`$1`,`$2`)'
})
]
...
};
module.exports = config;
//report.js
const report = (type, code) => {
console.log(type, ',', code)
...
}
export default report
//index.vue
import report from './report'
...
const handleClick = () => {
//>>>page,1
}
...
<template>
...
<div @click="handleClick">查看</div>
...
</template>
...
//打包之后注释 //>>>page,1 将被替换为report('page', '1')
//点击查看report将会被调用,控制台会打印出page,1
//也可以在入口将report挂载到window上,这样就不用导入,report可全局调用