【问题标题】:How come I can't find a module in nodejs?为什么我在 nodejs 中找不到模块?
【发布时间】:2015-09-23 18:57:07
【问题描述】:

所以我正在使用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,并且在服务器上使用时需要在另一个文件中很好。

【问题讨论】:

  • 很难说,您能以目录树的形式提供更多信息吗?也许满了checkout.jsx?您是否尝试要求绝对路径/app/scripts/components/checkout/layout?是 *.js 文件吗?

标签: javascript node.js express browserify


【解决方案1】:

您需要添加文件扩展名 (.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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-13
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多