1 | /**
|
2 | * Declares all globals with a var and assigns the global object. Thus you're able to
|
3 | * override globals without changing the global object itself.
|
4 | *
|
5 | * Returns something like
|
6 | * "var console = global.console; var process = global.process; ..."
|
7 | *
|
8 | * @return {String}
|
9 | */
|
10 | function getImportGlobalsSrc(ignore) {
|
11 | var key,
|
12 | src = "",
|
13 | globalObj = typeof global === "undefined"? window: global;
|
14 |
|
15 | ignore = ignore || [];
|
16 | ignore.push(
|
17 | // global itself can't be overridden because it's the only reference to our real global objects
|
18 | "global",
|
19 | // ignore 'module', 'exports' and 'require' on the global scope, because otherwise our code would
|
20 | // shadow the module-internal variables
|
21 | // @see https://github.com/jhnns/rewire-webpack/pull/6
|
22 | "module", "exports", "require",
|
23 | // strict mode doesn't allow to (re)define 'undefined', 'eval' & 'arguments'
|
24 | "undefined", "eval", "arguments",
|
25 | // 'GLOBAL' and 'root' are deprecated in Node
|
26 | // (assigning them causes a DeprecationWarning)
|
27 | "GLOBAL", "root",
|
28 | // 'NaN' and 'Infinity' are immutable
|
29 | // (doesn't throw an error if you set 'var NaN = ...', but doesn't work either)
|
30 | "NaN", "Infinity",
|
31 | );
|
32 |
|
33 | const globals = Object.getOwnPropertyNames(globalObj);
|
34 |
|
35 | for (key of globals) {
|
36 | if (ignore.indexOf(key) !== -1) {
|
37 | continue;
|
38 | }
|
39 |
|
40 | // key may be an invalid variable name (e.g. 'a-b')
|
41 | try {
|
42 | eval("var " + key + ";");
|
43 | src += "var " + key + " = global." + key + "; ";
|
44 | } catch(e) {}
|
45 | }
|
46 |
|
47 | return src;
|
48 | }
|
49 |
|
50 | module.exports = getImportGlobalsSrc;
|