I have a fictional utilities package (node module) that I'm importing into my apps like so:
var sqrt = require('common-math').sqrt
However, using this same module from within the common-math
module seems to be tricky. I seem to only have to options, both of which are not ideal:
require('../sqrt')
or require('../../../lib/sqrt')
. node_modules/sqrt/index.js
and then do a require('sqrt')
. I just want to be able to require('common-math').sqrt
just like all the consumers of this package do. I realize that I can create a node_modules/common-math
folder with a symlink to my package's index.js
, but is this a common/recommended practice?
Node's module loading system is very limited, but what you want is possible. However it is not as elegant as you might expect it to be:
var root = (function (p, path) {
for (; 'common-math' !== path.basename(p); p = path.dirname(p));
return p;
}(module.filename, require('path'));
var a = require(root + '/sqrt.js');
or even:
var root = (function (p) {
return p.slice(0, p.indexOf('common-math') + 1).join('/');
}(module.filename.split('/')));
var a = require(root + '/sqrt.js');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.