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

例如,如果查看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/


当前回答

我正在寻找完全相同的简单性,要求文件从任何级别,我发现模块-别名。

安装:

npm i --save module-alias

打开你的包裹。Json文件,在这里你可以为你的路径添加别名,例如。

"_moduleAliases": {
 "@root"      : ".", // Application's root
 "@deep"      : "src/some/very/deep/directory/or/file",
 "@my_module" : "lib/some-file.js",
 "something"  : "src/foo", // Or without @. Actually, it could be any string
}

使用你的别名只需:

require('module-alias/register')
const deep = require('@deep')
const module = require('something')

其他回答

还有:

var myModule = require.main.require('./path/to/module');

它需要的文件,就像它被要求从主js文件,所以它工作得很好,只要你的主js文件是在你的项目的根…这一点我很感激。

恕我直言,最简单的方法是将自己的函数定义为GLOBAL对象的一部分。 在项目的根目录下创建projRequire.js,包含以下内容:

var projectDir = __dirname;

module.exports = GLOBAL.projRequire = function(module) {
  return require(projectDir + module);
}

在你的主文件中,在需要任何特定于项目的模块之前:

// init projRequire
require('./projRequire');

之后,以下工作对我来说:

// main file
projRequire('/lib/lol');

// index.js at projectDir/lib/lol/index.js
console.log('Ok');

@Totty,我想出了另一个解决方案,可以解决你在评论中描述的情况。描述将是tl;dr,所以我最好展示我的测试项目的结构的图片。

如果你使用yarn而不是npm,你可以使用工作区。

假设我有一个文件夹服务,我希望更容易地需要:

.
├── app.js
├── node_modules
├── test
├── services
│   ├── foo
│   └── bar
└── package.json

要创建Yarn工作空间,需要创建一个包。services文件夹中的Json文件:

{
  "name": "myservices",
  "version": "1.0.0"
}

在你的主包里。json添加:

"private": true,
"workspaces": ["myservices"]

从项目的根目录运行yarn install。

然后,在代码的任何地方,你可以这样做:

const { myFunc } = require('myservices/foo')

而不是像这样:

const { myFunc } = require('../../../../../../services/foo')

虽然这些答案工作,但他们没有解决npm测试的问题

例如,如果我在server.js中创建一个全局变量,它将不会为我的测试套件执行设置。

设置全局apot变量,避免../../..在npm start和npm test中都可以使用,参见:

Mocha使用额外的选项或参数进行测试

请注意,这是新的官方摩卡解决方案。

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

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()