1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | const { ConcatSource } = require("webpack-sources");
|
8 |
|
9 |
|
10 |
|
11 | class SetVarMainTemplatePlugin {
|
12 | |
13 |
|
14 |
|
15 |
|
16 | constructor(varExpression, copyObject) {
|
17 |
|
18 | this.varExpression = varExpression;
|
19 |
|
20 | this.copyObject = copyObject;
|
21 | }
|
22 |
|
23 | |
24 |
|
25 |
|
26 |
|
27 | apply(compilation) {
|
28 | const { mainTemplate, chunkTemplate } = compilation;
|
29 |
|
30 | const onRenderWithEntry = (source, chunk, hash) => {
|
31 | const varExpression = mainTemplate.getAssetPath(this.varExpression, {
|
32 | hash,
|
33 | chunk
|
34 | });
|
35 | if (this.copyObject) {
|
36 | return new ConcatSource(
|
37 | `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `,
|
38 | source,
|
39 | "))"
|
40 | );
|
41 | } else {
|
42 | const prefix = `${varExpression} =\n`;
|
43 | return new ConcatSource(prefix, source);
|
44 | }
|
45 | };
|
46 |
|
47 | for (const template of [mainTemplate, chunkTemplate]) {
|
48 | template.hooks.renderWithEntry.tap(
|
49 | "SetVarMainTemplatePlugin",
|
50 | onRenderWithEntry
|
51 | );
|
52 | }
|
53 |
|
54 | mainTemplate.hooks.globalHashPaths.tap(
|
55 | "SetVarMainTemplatePlugin",
|
56 | paths => {
|
57 | if (this.varExpression) paths.push(this.varExpression);
|
58 | return paths;
|
59 | }
|
60 | );
|
61 | mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => {
|
62 | hash.update("set var");
|
63 | hash.update(`${this.varExpression}`);
|
64 | hash.update(`${this.copyObject}`);
|
65 | });
|
66 | }
|
67 | }
|
68 |
|
69 | module.exports = SetVarMainTemplatePlugin;
|