UNPKG

1.44 kBJavaScriptView Raw
1function isValidIdentifier(identifier) {
2 try {
3 // identifier may be an invalid variable name (e.g. 'a-b')
4 eval("var " + identifier + ";");
5 return true
6 } catch (e) {
7 return false;
8 }
9}
10
11/**
12 * Declares all globals with a var and assigns the global object. Thus you're able to
13 * override globals without changing the global object itself.
14 *
15 * Returns something like
16 * "var console = global.console; var process = global.process; ..."
17 *
18 * @return {String}
19 */
20function getImportGlobalsSrc(ignore) {
21 var key,
22 src = "",
23 globalObj = typeof global === "undefined"? window: global;
24
25 ignore = ignore || [];
26 // global itself can't be overridden because it's the only reference to our real global objects
27 ignore.push("global", "globalThis");
28 ignore.push("undefined");
29 // ignore 'module', 'exports' and 'require' on the global scope, because otherwise our code would
30 // shadow the module-internal variables
31 // @see https://github.com/jhnns/rewire-webpack/pull/6
32 ignore.push("module", "exports", "require");
33
34 for (key in Object.getOwnPropertyDescriptors(globalObj)) { /* jshint forin: false */
35 if (ignore.indexOf(key) !== -1) {
36 continue;
37 }
38
39 if (isValidIdentifier(key)) {
40 src += "var " + key + " = global." + key + "; ";
41 }
42 }
43
44 return src;
45}
46
47module.exports = getImportGlobalsSrc;