1.6.0 • Published 6 months ago
@liuyi_npm/html-webpack-extend-plugin v1.6.0
@liuyi_npm/html-webpack-extend-plugin
基于 html-webpack-plugin 的 webpack 插件,用于在 html 中插入自定义内容。
可用于根据 mode 自定义控制在 index.html 注入标签。
目前支持如下节点:
headbodyxhr: 向目标域发送请求,如果能够通,再渲染埋点
1.基础使用
执行以下 sh:
yarn add @liuyi_npm/html-webpack-extend-plugin -D配置分为两种:
constructorConfigfileConfig
如果 constructorConfig 不存在的话,则 fileConfig 是必需的。
当 constructorConfig 和 fileConfig 同时存在时,二者会进行追加合并。
1-2.fileConfig
推荐使用 fileConfig,项目更清晰,逻辑更易控。
1-2-1.函数形式(推荐)
module.exports = (runtimeInfo) => {
const {
env: { VUE_APP_TARGET }
} = runtimeInfo
if (VUE_APP_TARGET !== 'PROD') return {}
return {
head: [[]],
body: [[]],
xhr: [{}]
}
}1-2-2.对象形式
const isProd = process.env.VUE_APP_TARGET === 'PROD'
module.exports = {
head: isProd ? [
['script', { async: true, src: 'https://www.googletagmanager.com' }],
['script', {},
`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-6MCGJRJCR5');`
]
] : []
}1-3.constructorConfig
譬如,在项目中,如果只在生产环境下注入埋点脚本:
const HtmlWebpackExtendPlugin = require('@liuyi_npm/html-webpack-extend-plugin')
const isProd = process.env.VUE_APP_TARGET === 'PROD'
module.exports = {
plugins: [
new HtmlWebpackExtendPlugin({
head: isProd ? [
['script', { async: true, src: 'https://www.googletagmanager.com' }],
['script', {},
`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-6MCGJRJCR5');`
]
] : []
})
]
}2.Config
{
head: [
['tag', {}, 'innerHTML']
],
body: [
['tag', {}, 'innerHTML']
],
xhr: [{
method: 'GET',
url: '',
timeout: 3000,
nodes: [
['tag', {}, 'innerHTML']
]
}]
}3.配置文件
3-1.加载机制
优先级从上至下:
const searchPlaces = [
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.js`,
`.${moduleName}rc.ts`,
`${CONFIG_DIR_NAME}/${moduleName}rc`,
`${CONFIG_DIR_NAME}/${moduleName}rc.json`,
`${CONFIG_DIR_NAME}/${moduleName}rc.js`,
`${CONFIG_DIR_NAME}/${moduleName}rc.ts`,
`${moduleName}.config.js`,
`${moduleName}.config.ts`
]3-2.postinstall
安装依赖有三种方式:
yarn addpnpm addnpm install
当安装 @liuyi_npm/html-webpack-extend-plugin 时,如果本地项目不存在配置文件时,会执行 postinstall 钩子函数,以在项目根目录下创建一份配置模板。
详述安装的 3 种情况:
- 当项目第一次安装依赖时,一定会执行
postinstall - 假如项目中已经有依赖,再安装会升级版本,但不会执行
postinstall remove之后安装,默认也不会执行postinstall,需要手动清理缓存,譬如pnpm store prue
1.6.0
6 months ago