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

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


当前回答

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

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

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

其他回答

如果你的应用程序的入口点js文件(即你实际运行“node”的文件)在你的项目根目录下,你可以很容易地用rootpath npm模块做到这一点。只需通过

npm install --save rootpath

...然后在入口点js文件的最上面,添加:

require('rootpath')();

从那时起,所有的require调用现在都相对于项目根——例如require('../../../config/debugging/log');就要求(“配置/调试/日志”);(其中配置文件夹在项目根目录下)。

在Browserify手册中有一个非常有趣的章节:

avoiding ../../../../../../.. Not everything in an application properly belongs on the public npm and the overhead of setting up a private npm or git repo is still rather large in many cases. Here are some approaches for avoiding the ../../../../../../../ relative paths problem. node_modules People sometimes object to putting application-specific modules into node_modules because it is not obvious how to check in your internal modules without also checking in third-party modules from npm. The answer is quite simple! If you have a .gitignore file that ignores node_modules: node_modules You can just add an exception with ! for each of your internal application modules: node_modules/* !node_modules/foo !node_modules/bar Please note that you can't unignore a subdirectory, if the parent is already ignored. So instead of ignoring node_modules, you have to ignore every directory inside node_modules with the node_modules/* trick, and then you can add your exceptions. Now anywhere in your application you will be able to require('foo') or require('bar') without having a very large and fragile relative path. If you have a lot of modules and want to keep them more separate from the third-party modules installed by npm, you can just put them all under a directory in node_modules such as node_modules/app: node_modules/app/foo node_modules/app/bar Now you will be able to require('app/foo') or require('app/bar') from anywhere in your application. In your .gitignore, just add an exception for node_modules/app: node_modules/* !node_modules/app If your application had transforms configured in package.json, you'll need to create a separate package.json with its own transform field in your node_modules/foo or node_modules/app/foo component directory because transforms don't apply across module boundaries. This will make your modules more robust against configuration changes in your application and it will be easier to independently reuse the packages outside of your application. symlink Another handy trick if you are working on an application where you can make symlinks and don't need to support windows is to symlink a lib/ or app/ folder into node_modules. From the project root, do: ln -s ../lib node_modules/app and now from anywhere in your project you'll be able to require files in lib/ by doing require('app/foo.js') to get lib/foo.js. custom paths You might see some places talk about using the $NODE_PATH environment variable or opts.paths to add directories for node and browserify to look in to find modules. Unlike most other platforms, using a shell-style array of path directories with $NODE_PATH is not as favorable in node compared to making effective use of the node_modules directory. This is because your application is more tightly coupled to a runtime environment configuration so there are more moving parts and your application will only work when your environment is setup correctly. node and browserify both support but discourage the use of $NODE_PATH.

我喜欢为共享代码创建一个新的node_modules文件夹,然后让node和require做它最擅长的事情。

例如:

- node_modules // => these are loaded from your package.json
- app
  - node_modules // => add node-style modules
    - helper.js
  - models
    - user
    - car
- package.json
- .gitignore

例如,如果你在car/index.js中,你可以require('helper'), node会找到它!

node_modules如何工作

Node有一个在竞争对手中独一无二的解决模块的聪明算法 平台。

如果你从/beep/boop/bar.js中require('./foo.js'), node会在/beep/boop/foo.js中寻找。/foo.js。以./或..开头的路径/对于调用require()的文件总是本地的。

然而,如果你需要一个非相对名称,例如require('xyz')来自/beep/boop/foo.js, node会按顺序搜索这些路径,在第一次匹配时停止,如果没有找到就会引发错误:

/beep/boop/node_modules/xyz
/beep/node_modules/xyz
/node_modules/xyz

对于每个存在的xyz目录,node将首先查找一个xyz/包。查看是否存在一个“main”字段。“main”字段定义了如果你需要()目录路径,哪个文件应该负责。

例如,如果/beep/node_modules/xyz是第一个匹配,那么/beep/node_modules/xyz/package。json有:

{
  "name": "xyz",
  "version": "1.2.3",
  "main": "lib/abc.js"
}

然后从/beep/node_modules/xyz/lib/abc.js中导出的文件将被返回 要求(“xyz”)。

如果没有包裹。Json或没有“main”字段,index.js是假设的:

/beep/node_modules/xyz/index.js

我认为你不需要用你描述的方式来解决这个问题。如果您想在大量文件中更改相同的字符串,请使用sed。在你的例子中,

find . -name "*.js" -exec sed -i 's/\.\.\/\.\.\//\.\.\//g' {} +

/../变成了../

或者,您可以要求配置文件存储包含库路径的变量。如果您将以下文件存储为config.js在示例目录中

var config = {};
config.path = '../../';

在你的例子文件中

myConfiguration = require('./config');
express = require(config.path);

您将能够从一个文件控制每个示例的配置。

这只是个人喜好。

一些答案说,最好的方法是将代码作为包添加到node_module,我同意,这可能是最好的方法,失去../../../ in require,但实际上没有一个给出这样做的方法。

从2.0.0版本开始,你可以从本地文件安装一个包,这意味着你可以在根目录下创建一个文件夹,里面有你想要的所有包,

-modules
 --foo
 --bar 
-app.js
-package.json

所以在包装上。Json,你可以添加模块(或foo和bar)作为一个包,而不需要发布或使用外部服务器,像这样:

{
  "name": "baz",
  "dependencies": {
    "bar": "file: ./modules/bar",
    "foo": "file: ./modules/foo"
  }
}

之后你执行npm install,你可以使用var foo = require("foo")访问代码,就像你对所有其他包所做的一样。

更多信息可以在这里找到:

https://docs.npmjs.com/files/package.json#local-paths

下面是如何创建一个包:

https://docs.npmjs.com/getting-started/creating-node-modules