1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | 'use strict';
|
14 |
|
15 | var babylon = require('babylon'),
|
16 | inst = require('./install.js'),
|
17 | runOnce = false;
|
18 |
|
19 | global.requireHook = function (req) {
|
20 | if (!runOnce) {
|
21 | let newPath = process.env.NODE_PATH || '';
|
22 | if (newPath.length > 0) {
|
23 | newPath += /^win/.test(process.platform) ? ';' : ':';
|
24 | }
|
25 | newPath += global.rootPathJoin('node_modules');
|
26 | process.env.NODE_PATH = newPath;
|
27 | require('module').Module._initPaths();
|
28 | runOnce = true;
|
29 | }
|
30 |
|
31 | var func = function (mod) {
|
32 | return inst.requireOrInstall(req, mod);
|
33 | };
|
34 | for (var key in req) {
|
35 | func[key] = req[key];
|
36 | }
|
37 | func.safe = func;
|
38 |
|
39 | func.searchCache = function (moduleName, callback) {
|
40 | var mod = func.resolve(moduleName);
|
41 | if (mod && (typeof (mod = func.cache[mod]) !== 'undefined')) {
|
42 | (function run(mod) {
|
43 | mod.children.forEach(function (child) {
|
44 | run(child);
|
45 | });
|
46 | callback(mod);
|
47 | })(mod);
|
48 | }
|
49 | };
|
50 |
|
51 | func.uncache = function (moduleName) {
|
52 | func.searchCache(moduleName, function (mod) {
|
53 | delete func.cache[mod.id];
|
54 | });
|
55 |
|
56 | Object.keys(module.constructor._pathCache).forEach(function (cacheKey) {
|
57 | if (cacheKey.indexOf(moduleName) > 0) {
|
58 | delete module.constructor._pathCache[cacheKey];
|
59 | }
|
60 | });
|
61 | };
|
62 |
|
63 | func.reload = function (moduleName) {
|
64 | func.uncache(moduleName);
|
65 | return func(moduleName);
|
66 | };
|
67 |
|
68 | func.once = function (moduleName) {
|
69 | var mod = func(moduleName);
|
70 | func.uncache(moduleName);
|
71 | return mod;
|
72 | };
|
73 |
|
74 | return func;
|
75 | };
|
76 |
|
77 | module.exports = function () {
|
78 | return {
|
79 | visitor: {
|
80 | Program(path) {
|
81 | path.unshiftContainer('body', babylon.parse(module.exports.injectionString).program.body[0]);
|
82 | }
|
83 | }
|
84 | };
|
85 | };
|
86 |
|
87 | module.exports.injectionString = 'require = (global || GLOBAL).requireHook(require);';
|
88 |
|
89 | exports.default = module.exports;
|