我想要求我的文件总是通过我的项目的根,而不是相对于当前模块。

例如,如果查看https://github.com/visionmedia/express/blob/2820f2227de0229c5d7f28009aa432f9f3a7b5f9/examples/downloads/app.js第6行,您将看到

express = require('../../')

在我看来,这真的很糟糕。假设我想让我所有的例子都只靠近根结点一层。这是不可能的,因为我必须更新超过30个例子,并且在每个例子中更新很多次。:

express = require('../')

我的解决方案是有一个基于根的特殊情况:如果字符串以$开头,那么它相对于项目的根文件夹。

任何帮助都是感激的,谢谢

更新2

现在我使用require.js,它允许你以一种方式编写,在客户端和服务器上都可以工作。Require.js还允许你创建自定义路径。

更新3

现在我转移到webpack + gulp,我使用enhanced-require来处理服务器端模块。看这里的基本原理:http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/


当前回答

我实现这一点的方法是创建“本地链接模块”。

的文件夹结构为例

db ¬ 
    models ¬
        index.js
    migrations
    seed
    config.json

routes ¬
    index.js
    user ¬
        index.js

如果从。/routes/user/index.js我想访问/db/models/index.js我会写

require('../../db/models/index.js')

为了使/db/models/index.js可以从任何地方访问,我在db文件夹中创建了一个名为_module_的文件夹,其中包含一个包。Json和一个main.js文件。

# package.json
{
    "name": "db", <-- change this to what you want your require name to be
    "version": "1.0.0",
    "description": "",
    "author": "",
    "repository": {},
    "main": "main.js"
}
// main.js
module.exports = require('../../db/models/index');

main.js中的路径必须是相对的,就像文件在node_modules中一样

node_modules ¬
    db ¬
        main.js

然后你可以运行npm install ./db/_module_,这将把。/db/_module_中的文件复制到。/node_modules/db中,在应用程序包的依赖项下创建一个条目。json之类的

"db": "file:db/_module_"

您现在可以在任何地方使用此包

const db = require('db');

当你运行npm install时,它会自动安装你的其他模块,工作跨平台(没有符号链接),并且不需要第三方包。

其他回答

你可以在app.js中定义这样的东西:

requireFromRoot = (function(root) {
    return function(resource) {
        return require(root+"/"+resource);
    }
})(__dirname);

然后任何时候你想从根目录中要求一些东西,无论你在哪里,你只需要使用requireFromRoot而不是普通的require。到目前为止对我来说还不错。

我在我的项目中使用process.cwd()。例如:

var Foo = require(process.cwd() + '/common/foo.js');

值得注意的是,这将导致需要一个绝对路径,尽管我还没有在这方面遇到问题。

我尝试过很多这样的解决方案。我最终把这个添加到我的主文件的顶部(例如index.js):

process.env.NODE_PATH = __dirname;
require('module').Module._initPaths();

这将在加载脚本时将项目根添加到NODE_PATH。允许我通过引用项目根的相对路径,如var User = require('models/ User '),来要求项目中的任何文件。只要在项目中运行其他任何东西之前在项目根目录中运行一个主脚本,这个解决方案就应该有效。

我编写了这个小包,它允许您通过项目根的相对路径来要求包,而不引入任何全局变量或覆盖节点默认值

https://github.com/Gaafar/pkg-require

它是这样工作的

// create an instance that will find the nearest parent dir containing package.json from your __dirname
const pkgRequire = require('pkg-require')(__dirname);

// require a file relative to the your package.json directory 
const foo = pkgRequire('foo/foo')

// get the absolute path for a file
const absolutePathToFoo = pkgRequire.resolve('foo/foo')

// get the absolute path to your root directory
const packageRootPath = pkgRequire.root()

刚刚看到这篇文章提到了app-module-path。它允许你这样配置一个基础:

require('app-module-path').addPath(baseDir);