编写commonjs模块并使用require来加载它(不使用相对path)

在不使用相对path的情况下引用本地commonjs模块的最佳实践是什么?

var custMod= require('customModule'); custMod(true); custMod.save('foo'); 

有没有build立这样的模块的任何参考?

如果我写下面的模块,当我调用custMode.save(12);

 module.exports = customModule;function customModule(mode) { var mode = 1; return { save: function (value) { console.log(mode, value) }, get: function (id) { console.log(mode, id) } } 

您可以添加require检查的path

 require.paths.push('/my/path'); 

要么

 require.main.paths.push('/my/path'); 

取决于您的节点版本。

那么如果customModule.js存在于/my/path/customModule.js ,那么你可以直接使用

 require('customModule'); 

但请注意,您需要在您打算使用此方法的每个模块上执行此操作。

我希望节点更容易说实话。 一种可能性:

 project_root `--node_modules |--npm-module-1 |--npm-module-2 |--... (etc) `--lib |--my-module.js `--my-other-module.js 

通过上述操作,您可以在项目的任何位置inputrequire('lib/my-module') 。 (只要确保不要安装名为lib的npm模块:)另一种可能性:

 project_root |--node_modules | |--npm-module-1 | |--npm-module-2 | `--... (etc) `--lib `--node_modules |--my-module.js `--my-other-module.js 

有了上面的代码,你可以inputrequire('my-module') ,但只能用于project_root/lib/下的任何文件。

前一种方法的一个优点是require('lib/my-module')使得一目了然地知道哪些模块是本地项目是非常容易的。 但后者更less打字。