UNPKG

1.79 kBJavaScriptView Raw
1var Module = require("module"),
2 fs = require("fs"),
3 getImportGlobalsSrc = require("./getImportGlobalsSrc.js"),
4 getDefinePropertySrc = require("./getDefinePropertySrc.js"),
5 detectStrictMode = require("./detectStrictMode.js"),
6 moduleEnv = require("./moduleEnv.js");
7
8/**
9 * Does actual rewiring the module. For further documentation @see index.js
10 */
11function internalRewire(parentModulePath, targetPath) {
12 var targetModule,
13 prelude,
14 appendix,
15 src;
16
17 // Checking params
18 if (typeof targetPath !== "string") {
19 throw new TypeError("Filename must be a string");
20 }
21
22 // Resolve full filename relative to the parent module
23 targetPath = Module._resolveFilename(targetPath, parentModulePath);
24
25 // Create testModule as it would be created by require()
26 targetModule = new Module(targetPath, parentModulePath);
27
28 // We prepend a list of all globals declared with var so they can be overridden (without changing original globals)
29 prelude = getImportGlobalsSrc();
30
31 // Wrap module src inside IIFE so that function declarations do not clash with global variables
32 // @see https://github.com/jhnns/rewire/issues/56
33 prelude += "(function () { ";
34
35 // We append our special setter and getter.
36 appendix = "\n" + getDefinePropertySrc();
37
38 // End of IIFE
39 appendix += "})();";
40
41 // Check if the module uses the strict mode.
42 // If so we must ensure that "use strict"; stays at the beginning of the module.
43 src = fs.readFileSync(targetPath, "utf8");
44 if (detectStrictMode(src) === true) {
45 prelude = ' "use strict"; ' + prelude;
46 }
47
48 moduleEnv.inject(prelude, appendix);
49 moduleEnv.load(targetModule);
50
51 return targetModule.exports;
52}
53
54module.exports = internalRewire;