-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (75 loc) · 2.4 KB
/
index.js
File metadata and controls
85 lines (75 loc) · 2.4 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
const vm = require('vm');
function RequireJsResolverPlugin(options) {
this.configPath = options.configPath;
this.sandbox = options.sandbox || {};
}
RequireJsResolverPlugin.prototype.getConfig = function (fs) {
return new Promise((resolve, reject) => {
if (this.configData) {
return resolve(this.configData);
}
fs.readFile(this.configPath, (err, buffer) => {
if (err) {
reject(err);
} else {
resolve(buffer.toString('utf8'));
}
});
}).then(code => {
if (this.configData) {
return this.configData;
}
let sandbox = Object.assign({
paths: {},
require: () => {
},
}, this.sandbox);
sandbox.require.addPaths = function (paths) {
for (let path in paths) {
sandbox.paths[path] = paths[path];
}
};
sandbox.require.config = function (config) {
if (config.paths) {
this.addPaths(config.paths);
}
// Used by Magento.
if (config.map && config.map['*']) {
this.addPaths(config.map['*']);
}
};
vm.runInNewContext(code, sandbox, {
filename: this.configPath,
displayErrors: true,
});
this.configData = sandbox.paths;
return this.configData;
});
};
function registerHook(object, oldName, newName, cb) {
if (object.hooks) {
object.hooks[newName].tapAsync('RequireJsResolverPlugin', cb);
} else {
object.plugin(oldName, cb);
}
}
RequireJsResolverPlugin.prototype.apply = function (resolver) {
const target = resolver.ensureHook('resolve');
registerHook(resolver, 'module', 'module', (request, resolveContext, callback) => {
if (!callback) {
callback = resolveContext;
}
this.getConfig(resolver.fileSystem).then(config => {
if (config[request.request]) {
const nextRequest = Object.assign({}, request, { request: config[request.request] });
return resolver.doResolve(target, nextRequest, 'mapping via requirejs-config', callback);
} else {
callback();
}
}, err => {
callback(err);
});
});
};
module.exports = RequireJsResolverPlugin;