我找到了方法,只是有点内部结构。解决方案草案:
Module = require('module');
Module.prototype.requireOrig = Module.prototype.require;
Module.prototype.require = (path) ->
console.log('Importing ' + path + '...');
return this.require(path)
Here 是Module 类的源代码。
更新:这就是我的结束。它做的很简单——当需要以 ':/' 开头的模块时(例如 ':/foo/bar'),按照它们相对于主模块的方式查找它们。
Module = require 'module'
assert = require 'assert'
do ->
origRequire = Module::require
_require = (context, path) -> origRequire.call context, path
main = require.main
Module::require = (path) ->
assert typeof path == 'string', 'path must be a string'
assert path, 'missing path'
if path[...2] == ':/'
return _require main, "./#{path[2...]}"
return _require @, path
上面sn-p的等效Javascript:
var Module = require('module');
var assert = require('assert');
(function() {
var origRequire = Module.prototype.require;
var _require = function(context, path) {
return origRequire.call(context, path);
};
var main = require.main;
Module.prototype.require = function(path) {
assert(typeof path === 'string', 'path must be a string');
assert(path, 'missing path');
if (path.slice(0, 2) === ':/') {
return _require(main, "./" + path.slice(2));
}
return _require(this, path);
};
})();