1 |
3a515b92
|
cagy
|
/*
|
2 |
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3 |
|
|
Author Tobias Koppers @sokra
|
4 |
|
|
*/
|
5 |
|
|
"use strict";
|
6 |
|
|
|
7 |
|
|
const { ConcatSource } = require("webpack-sources");
|
8 |
|
|
|
9 |
|
|
/** @typedef {import("./Compilation")} Compilation */
|
10 |
|
|
|
11 |
|
|
class SetVarMainTemplatePlugin {
|
12 |
|
|
/**
|
13 |
|
|
* @param {string} varExpression the accessor where the library is exported
|
14 |
|
|
* @param {boolean} copyObject specify copying the exports
|
15 |
|
|
*/
|
16 |
|
|
constructor(varExpression, copyObject) {
|
17 |
|
|
/** @type {string} */
|
18 |
|
|
this.varExpression = varExpression;
|
19 |
|
|
/** @type {boolean} */
|
20 |
|
|
this.copyObject = copyObject;
|
21 |
|
|
}
|
22 |
|
|
|
23 |
|
|
/**
|
24 |
|
|
* @param {Compilation} compilation the compilation instance
|
25 |
|
|
* @returns {void}
|
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;
|