UNPKG

aiot-qiankun-ucf-scripts

Version:
50 lines (47 loc) 1.5 kB
/** * 此插件依赖htmtwebpackplugin插件先运行,将处理html的钩子htmlWebpackPluginBeforeHtmlProcessing注册到compilation,本插件才能运行; * 可支持配置传递; * needConsul作为是否开启consul对接的标志位,不需要可关闭,采用本地配置; * contxt作为配置中心配置项目code */ class AlterHtmlContentPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( 'AlterHtmlContentPlugin', (compilation) => { console.log('The compiler is starting a new compilation...'); let { context, consul } = this.options; const {needConsul, consulService} = consul compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tap( 'AlterHtmlContentPlugin', // <-- Set a meaningful name here for stacktraces (data, cb) => { // Manipulate the content let reg = new RegExp( /([\s\S]*?<body[\s\S]*?>)([\s\S]*?)(<\/body>[\s\S]*?)/gi ); let scriptContent = `<script> function setConfig(cfg) { if(!cfg){ return; } for (let item of cfg) { window[item.name] = item.value; } } </script> <script src="${consulService}/api/v1/config/${context}?callback=setConfig"></script>`; needConsul && (data.html = data.html.replace( reg, `$1$2${scriptContent}$3` )); } ); } ); } } module.exports = AlterHtmlContentPlugin;