From 4dd71d7113711e66f82f65d57aeb9d5ae8e44f8e Mon Sep 17 00:00:00 2001 From: novlan1 <1576271227@qq.com> Date: Fri, 17 Mar 2023 16:06:07 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96replace-content?= =?UTF-8?q?=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/replace-content/replace-content.ts | 58 +++++++++++++---------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/plugin/replace-content/replace-content.ts b/plugin/replace-content/replace-content.ts index eae595d..f5832c5 100644 --- a/plugin/replace-content/replace-content.ts +++ b/plugin/replace-content/replace-content.ts @@ -5,8 +5,10 @@ replaceAllPolyfill(); function replaceContent({ content, reg, fileName }) { if (reg.test(content)) { console.log('[ReplaceContentPlugin] 处理了文件:', fileName); + return content.replaceAll(reg, ''); } - return content.replaceAll(reg, ''); + + return content; } export class ReplaceContentPlugin { @@ -20,32 +22,40 @@ export class ReplaceContentPlugin { } apply(complier) { - const { fileNameReg, replaceReg } = this; complier.hooks.emit.tapAsync('ReplaceContentPlugin', (compilation, cb) => { - const fileNames = Object.keys(compilation.assets); - for (const fileName of fileNames) { - if (!fileNameReg.test(fileName)) { - continue; - } - - const asset = compilation.assets[fileName]; - if (asset._valueIsBuffer) { - continue; - } - - const sourceCode = asset.source() || asset._valueAsString || asset._value || asset._cachedSource; - - if (sourceCode != null) { - // 这里返回null或者undefined会导致编译过程无法结束,所以sourceCode需要判空才给asset.source赋值 - asset.source = () => replaceContent({ - content: sourceCode, - reg: replaceReg, - fileName, - }); - } + try { + this.doReplace(compilation, cb); + } catch (err) { + console.log('[ReplaceContentPlugin] err: ', err); } - cb?.(); }); } + + doReplace(compilation, cb) { + const { fileNameReg, replaceReg } = this; + const fileNames = Object.keys(compilation.assets); + for (const fileName of fileNames) { + if (!fileNameReg.test(fileName)) { + continue; + } + + const asset = compilation.assets[fileName]; + if (asset._valueIsBuffer) { + continue; + } + + const sourceCode = asset.source() || asset._valueAsString || asset._value || asset._cachedSource; + + if (sourceCode != null) { + // 这里返回null或者undefined会导致编译过程无法结束,所以sourceCode需要判空才给asset.source赋值 + asset.source = () => replaceContent({ + content: sourceCode, + reg: replaceReg, + fileName, + }); + } + } + cb?.(); + } }