UNPKG

2.48 kBJavaScriptView Raw
1/**
2 * Script to extend require, allowing us to reload javascript code
3 * without doing a hard reset on the application.
4 *
5 * Written By:
6 * Matthew Knox
7 *
8 * License:
9 * MIT License. All code unless otherwise specified is
10 * Copyright (c) Matthew Knox and Contributors 2016.
11 */
12
13'use strict';
14
15var babylon = require('babylon'),
16 inst = require('./install.js'),
17 runOnce = false;
18
19global.requireHook = function (req) {
20 if (!runOnce) { // prevent re-init
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
77module.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
87module.exports.injectionString = 'require = (global || GLOBAL).requireHook(require);';
88
89exports.default = module.exports;