File: getImportGlobalsSrc.js

package info (click to toggle)
node-rewire 6.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 392 kB
  • sloc: javascript: 1,386; makefile: 2
file content (50 lines) | stat: -rw-r--r-- 1,688 bytes parent folder | download
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
46
47
48
49
50
/**
 * Declares all globals with a var and assigns the global object. Thus you're able to
 * override globals without changing the global object itself.
 *
 * Returns something like
 * "var console = global.console; var process = global.process; ..."
 *
 * @return {String}
 */
function getImportGlobalsSrc(ignore) {
    var key,
        src = "",
        globalObj = typeof global === "undefined"? window: global;

    ignore = ignore || [];
    ignore.push(
        // global itself can't be overridden because it's the only reference to our real global objects
        "global",
        // ignore 'module', 'exports' and 'require' on the global scope, because otherwise our code would
        // shadow the module-internal variables
        // @see https://github.com/jhnns/rewire-webpack/pull/6
        "module", "exports", "require",
        // strict mode doesn't allow to (re)define 'undefined', 'eval' & 'arguments'
        "undefined", "eval", "arguments",
        // 'GLOBAL' and 'root' are deprecated in Node
        // (assigning them causes a DeprecationWarning)
        "GLOBAL", "root",
        // 'NaN' and 'Infinity' are immutable
        // (doesn't throw an error if you set 'var NaN = ...', but doesn't work either)
        "NaN", "Infinity",
    );

    const globals = Object.getOwnPropertyNames(globalObj);

    for (key of globals) {
        if (ignore.indexOf(key) !== -1) {
            continue;
        }

        // key may be an invalid variable name (e.g. 'a-b')
        try {
          eval("var " + key + ";");
          src += "var " + key + " = global." + key + "; ";
        } catch(e) {}
    }

    return src;
}

module.exports = getImportGlobalsSrc;