为什么我在 nodejs 中找不到模块?

How come I can't find a module in nodejs?

所以我正在 https://github.com/mhart/react-server-example/blob/master/server.js 研究 React 中的服务器端渲染。它利用了 browserify。

该示例是一个平面文件夹结构,因为它只是一个示例。所以下面是我的一些让我感到困惑的更改。

/server/controllers/bundles.jsx 有这个

browserify()
  .add('./app/scripts/checkout.jsx')
  .transform(literalify.configure({
    'react': 'window.React',
    'react-dom': 'window.ReactDOM',
  }))
  .bundle()
  .pipe(res)

此时我了解到,即使我嵌套在一个文件夹中,browserify 仍在根目录下工作。同时在 checkout.jsx 里面我有这个:

require('./app/scripts/components/checkout/layout');

当我启动我的服务器时,找不到文件。我也尝试做 ./components/checkout/layout 因为那是它相对于 checkout.jsx.

的位置

无论我怎么尝试,我的服务器都说找不到布局模块。

更新 我为 __dirname 添加了 console.log 并看到了 /app/scripts 所以这让我觉得 require('components/checkout/layout') 应该点击 /app/scripts/components/checkout/layout 但还是没找到。我还应该注意到该文件确实 module.exports = Layout 并且在服务器上使用时在另一个文件中被要求很好。

您需要添加文件扩展名(.jsx)。

基本上,节点中的 require 有一堆规则,all outlined in the docs here

对于你的情况,最相关的是这部分:

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text.  STOP
2. If X.js is a file, load X.js as JavaScript text.  STOP
3. If X.json is a file, parse X.json to a JavaScript Object.  STOP
4. If X.node is a file, load X.node as binary addon.  STOP

您正在点击 #2,然后转到 LOAD_AS_FILE,默认情况下没有 jsx 文件,因此您需要扩展名以使其与 #1 匹配。