gpt4 book ai didi

javascript - 当另一个模块需要时, Node 如何解析模块位置?

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:33 24 4
gpt4 key购买 nike

我有以下目录和文件

/path/to/dir1
/path/to/dir1/server.js
/path/to/dir1/package.json
/path/to/dir1/node_modules

/path/to/dir2/moduleA.js

然后我有 moduleA.js,它是这样开始的:

var React = require('react');

我的 package.json 文件如下所示:

{
"dependencies": {
"react": "^0.10.0"
}
}

如果我这样做,现在从 server.js 中:

要求('../dir2/moduleA')

它将找到 moduleA,但随后在 moduleA 中我有 require('react'),它实际上驻留在 node_modules 文件夹中与 server.js 相同的目录中。然而,这个位置没有被搜索到,我收到一个错误

错误:找不到模块“react”

我认为解析 require 语句时搜索的位置之一是当前正在执行的进程的 node_modules 目录?为什么这不起作用?

最佳答案

来自documentation :

Loading from node_modules Folders

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.

For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then node would look in the following locations, in this order:

/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js

This allows programs to localize their dependencies, so that they do not clash.

即它会在 /path/to/dir2/node_modules/path/to/node_modules 等中查找,但不会在 /path/to/dir1/node_modules 中查找

关于javascript - 当另一个模块需要时, Node 如何解析模块位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24590734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com