nodejs - what to use instead of require.paths?

2020-06-15 04:37发布

Recent node docs say that modifying require.paths is bad practice. What should I do instead?

标签: node.js
4条回答
狗以群分
2楼-- · 2020-06-15 05:08

I keep the related models in the same dir or a sub dir and load using:

var x = require('./mod/x');

In case it's an external module, I install it using npm that puts the module correctly in NODE_PATH.

I've never changed require.paths.

查看更多
我只想做你的唯一
3楼-- · 2020-06-15 05:12

I believe the concern is that it can be repeatedly modified at run time, rather than just set. That could obviously be confusing and causes some quite bizarre bugs. Also, if individual packages modify the path the results are applied globally, which is really bad and goes against the modular nature of node.

If you have several library paths of your own, the best solution is to set the NODE_PATH environment variable before launching node. Node then picks this up when it's launched and applies it automatically.

查看更多
走好不送
4楼-- · 2020-06-15 05:28

Unless I'm making a mistake in my understanding, the primary limitation of the current system is that for namespacing you're stuck without the uses of folders for non-hierarchical dependencies.

What that means in practice...

Consider that you have x/y/z and a/b as well as a/b/c. If both a/b and a/b/c depend on z/y/z you end up having to either specify that relatively (require('../../x/y/z') and require('../../../x/y/z') respectively) or having to make every single package a node_module. Failing that you can probably do horrific things with symlinks or similar.

As far as I can tell the only alternative is to rather than use folders to namespace and organise, use filenames such as:

  • a.b.js
  • a.b.c.js
  • x.y.z.js
查看更多
干净又极端
5楼-- · 2020-06-15 05:31

have a look at https://github.com/patrick-steele-idem/app-module-path-node; you can add a directory to the require statements in the top level, without influencing the paths of sub-modules.

查看更多
登录 后发表回答