Add module itself when resolving NODE_PATH

32 views
Skip to first unread message

Jesús Leganés Combarro

unread,
Feb 15, 2014, 10:27:35 AM2/15/14
to nod...@googlegroups.com
As asked for at https://github.com/joyent/node/issues/7126, when defining tests and examples on a Node.js package, you can't be able to require() the package itself, needing to do it directly over the Javascript files. It's said, instead of
var myModule = require('myModule');
you needs to do
var myModule = require('../lib/index.js');
This has the problem that both examples and tests doesn't follow the same behaviour than third party code that makes use of that module, leading to problems and also making it inconsistent since you can require() other modules that are on the node_modules folder. To fix this, I propose that require() resolve algorythm takes in account also the current package when searching for modules. This should be easy, since when scaling over the filesystem hierarchy this is located in the same point where a package.json file or a node_modules folder is found, so it would only need to check for the current package before going into the node_modules folder. Another alternative would be to add dinamically the current package root folder to the NODE_PATH environment variable.

Following advice from @indutny on the GitHub issue pointed before, I've open this topic for discussion about if this should be implemented.

mscdex

unread,
Feb 15, 2014, 3:38:27 PM2/15/14
to nod...@googlegroups.com
On Saturday, February 15, 2014 10:27:35 AM UTC-5, Jesús Leganés Combarro wrote:
As asked for at https://github.com/joyent/node/issues/7126, when defining tests and examples on a Node.js package, you can't be able to require() the package itself, needing to do it directly over the Javascript files. It's said, instead of
var myModule = require('myModule');
you needs to do
var myModule = require('../lib/index.js');


If you have your 'main' in package.json already set to 'lib/index.js', then all you need to do is `var myModule = require('..');` if you are one level within the package/module root. To me, that's easy enough. Also it's not as if end users of the module will have to be dealing with this problem, so for me the issue isn't that big of a deal.

Jesús Leganés Combarro

unread,
Feb 15, 2014, 4:06:17 PM2/15/14
to nod...@googlegroups.com
I tested what you said and it working, I didn't think about using require() in this way :-) I still think that this use case should be considered, but it's true that the vast majority of end users will not face with this issue and the two-dots trick can be a good solution, so maybe it's good for now.
Reply all
Reply to author
Forward
0 new messages