blob: 43c5d9f6226b49fa17475e6170a8b7f59267685f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import webpack from "webpack";
import path from "path";
import { getFileName } from "../utils/build-file.js";
import { getInjectedCode } from "../utils/injected-code.js";
/**
* Webpack plugin that post-processes every `.js` asset to replace
* extension-asset URL placeholders with runtime lookup code, and
* emits an additional "injected" script that the content script
* injects into the page via the script-injector module.
*/
class InjectScriptPlugin {
/**
* @param {import("webpack").Compiler} compiler
*/
apply(compiler) {
compiler.hooks.compilation.tap("InjectScriptPlugin", compilation => {
compilation.hooks.processAssets.tapPromise(
{
name: "InjectScriptPlugin",
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
additionalAssets: true
},
async assets => {
for (const assetName in assets) {
if (/\.js$/.test(assetName)) {
const injectedCodeResponse = getInjectedCode(compilation.getAsset(assetName).source.source())
const scriptInjectorModuleName = getFileName("script-injector", "shared", true);
compilation.updateAsset(
assetName,
new webpack.sources.RawSource(injectedCodeResponse[0])
);
assets["scripts/" + path.basename(assetName)] = new webpack.sources.RawSource(
`$${scriptInjectorModuleName}.injectScriptHead("scripts/injected/${path.basename(assetName)}", ${injectedCodeResponse[1]});`
);
}
}
}
);
});
}
}
export default InjectScriptPlugin;
|