|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const vm = require('vm'); |
| 4 | + |
| 5 | +function RequireJsResolverPlugin(options) { |
| 6 | + this.configPath = options.configPath; |
| 7 | +} |
| 8 | + |
| 9 | +RequireJsResolverPlugin.prototype.getConfig = function(fs) { |
| 10 | + return new Promise((resolve, reject) => { |
| 11 | + if (this.configData) { |
| 12 | + return resolve(this.configData); |
| 13 | + } |
| 14 | + |
| 15 | + fs.readFile(this.configPath, function(err, buffer) { |
| 16 | + if (err) { |
| 17 | + reject(err); |
| 18 | + } else { |
| 19 | + resolve(buffer.toString('utf8')); |
| 20 | + } |
| 21 | + }); |
| 22 | + }).then(code => { |
| 23 | + if (this.configData) { |
| 24 | + return this.configData; |
| 25 | + } |
| 26 | + |
| 27 | + var sandbox = { |
| 28 | + paths: {}, |
| 29 | + require: function() { |
| 30 | + }, |
| 31 | + }; |
| 32 | + sandbox.require.addPaths = function(paths) { |
| 33 | + for (var path in paths) { |
| 34 | + sandbox.paths[path] = paths[path]; |
| 35 | + } |
| 36 | + }; |
| 37 | + sandbox.require.config = function(config) { |
| 38 | + if (config.paths) { |
| 39 | + this.addPaths(config.paths); |
| 40 | + } |
| 41 | + |
| 42 | + // Used by Magento. |
| 43 | + if (config.map && config.map['*']) { |
| 44 | + this.addPaths(config.map['*']); |
| 45 | + } |
| 46 | + }; |
| 47 | + vm.runInNewContext(code, sandbox, { |
| 48 | + filename: this.configPath, |
| 49 | + displayErrors: true, |
| 50 | + }); |
| 51 | + |
| 52 | + this.configData = sandbox.paths; |
| 53 | + return this.configData; |
| 54 | + }); |
| 55 | +}; |
| 56 | + |
| 57 | +RequireJsResolverPlugin.prototype.apply = function(resolver) { |
| 58 | + resolver.plugin('module', (request, callback) => { |
| 59 | + this.getConfig(resolver.fileSystem).then(config => { |
| 60 | + if (config[request.request]) { |
| 61 | + var nextRequest = Object.assign({}, request, { request: config[request.request] }); |
| 62 | + return resolver.doResolve('resolve', nextRequest, 'mapping via requirejs-config', function(err, result) { |
| 63 | + callback(err, result); |
| 64 | + }); |
| 65 | + } else { |
| 66 | + callback(); |
| 67 | + } |
| 68 | + }) |
| 69 | + }); |
| 70 | +}; |
| 71 | + |
| 72 | +module.exports = RequireJsResolverPlugin; |
0 commit comments