开发者

accessing modules relatively from a fixed root with require in nodeJS

开发者 https://www.devze.com 2023-01-28 06:31 出处:网络
I\'m trying to access modules but the nesting gets a bit out of hand require(\"../../../Folder/Deeper/someFile\")

I'm trying to access modules but the nesting gets a bit out of hand

require("../../../Folder/Deeper/someFile")

Is there anyway to just use require("Folder/Deeper/somefile")

I've tried setting

require.paths = ['/media/work/Project'];

but that doesn't seem to 开发者_Go百科work and also feels a bit ugly to me.

Are there any alternatives. Is there any way to write a wrapper for this?


Maybe this?

require.paths.unshift( '../../..' );
require("Folder/Deeper/somefile");

http://nodejs.org/api.html says:

require.paths An array of search paths for require(). This array can be modified to add custom paths.

Example: add a new path to the beginning of the search list

require.paths.unshift('/usr/local/node');


Put your application into one folder in the app root (say, ./app), then soft-link it into node_modules like so:

ln -s ../app ./node_modules

(Note the double dot before app.)

This will allow you to require modules from your application root:

require('app/route/api')

For convenience, include this into package.json as a postinstall script to run on each npm install:

"scripts": {
  "postinstall": "ln -sf ../app ./node_modules"
}

Windows doesn't have ln, so Windows users will need to make a symlink manually. It may or may not work on Windows.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号