From 34ad953c953a395ba3e51c8125034a6bb65b2a79 Mon Sep 17 00:00:00 2001 From: Arpit Chakladar <54011232+arpitchakladar@users.noreply.github.com> Date: Mon, 13 Feb 2023 22:49:42 +0530 Subject: Fixed not being able to import modules in scripts. --- .../get-injection-code.js | 1 + .../plugins/inject-script-webpack-plugin/index.js | 30 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 config/webpack/plugins/inject-script-webpack-plugin/get-injection-code.js create mode 100644 config/webpack/plugins/inject-script-webpack-plugin/index.js (limited to 'config/webpack/plugins/inject-script-webpack-plugin') diff --git a/config/webpack/plugins/inject-script-webpack-plugin/get-injection-code.js b/config/webpack/plugins/inject-script-webpack-plugin/get-injection-code.js new file mode 100644 index 0000000..90a1cb7 --- /dev/null +++ b/config/webpack/plugins/inject-script-webpack-plugin/get-injection-code.js @@ -0,0 +1 @@ +module.exports = code => `const o=new MutationObserver(()=>{let t=document.querySelector("head > script:nth-child(54)");if(t){let e=\`(()=>{${code.replaceAll("`","\\`")}})();\`;null==t.getAttribute("data-replaced")?(t.innerHTML=e,t.setAttribute("data-replaced","")):t.innerHTML+=e,o.disconnect()}});o.observe(document,{childList:!0,subtree:!0});`; diff --git a/config/webpack/plugins/inject-script-webpack-plugin/index.js b/config/webpack/plugins/inject-script-webpack-plugin/index.js new file mode 100644 index 0000000..b7b5940 --- /dev/null +++ b/config/webpack/plugins/inject-script-webpack-plugin/index.js @@ -0,0 +1,30 @@ +const { sources } = require("webpack"); +const terser = require("terser"); + +const getInjectionCode = webpackRequire("plugins/inject-script-webpack-plugin/get-injection-code"); + +class InjectScriptPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("InjectScriptPlugin", compilation => { + compilation.hooks.processAssets.tapPromise( + { + name: "InjectScriptPlugin", + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, + additionalAssets: true + }, + async assets => { + for (const assetName in assets) { + if (assetName.endsWith("injected.js")) { + compilation.updateAsset( + assetName, + new sources.RawSource(getInjectionCode(compilation.getAsset(assetName).source.source())) + ); + } + } + } + ); + }); + } +} + +module.exports = InjectScriptPlugin; -- cgit v1.2.3