【问题标题】:Requiring CoffeeScript from Node.js application gives cannot find module error从 Node.js 应用程序需要 CoffeeScript 会导致找不到模块错误
【发布时间】:2015-04-10 23:45:09
【问题描述】:

我正在尝试从 Node.js 应用程序中获取 CoffeeScript 文件,但 Node.js 给出错误 Error: Cannot find module 'something'。这样做的正确方法是什么?如果我事先编译 CoffeeScript 代码,它可以工作,但我不想这样做。

test.js:

require('coffee-script').register();

require('something');

something.coffee:

console.log('Hello World!');

控制台输出:

> node test.js

module.js:340
    throw err;
          ^
Error: Cannot find module 'something'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (C:\Users\Sami\Desktop\smallscale\test.js:3:1)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:906:3

【问题讨论】:

  • 你也反对编译它的监视进程?
  • @DaveNewton 我发现多个答案表明这应该是可能的。参见例如stackoverflow.com/a/4769079/2193958
  • 为什么不试试上面所说的呢?我总是有一个观察者在进行 linting 和编译,所以我不太了解按需编译——抱歉。

标签: node.js coffeescript


【解决方案1】:

您似乎正在尝试使用require() 模块的结构来require() 一个文件。

如果你 require() 没有给 require() 一个文件路径(绝对或相对),Node.js 将在 /node_modules 目录中查找你的模块。你可以阅读文档here

尝试将您的模块要求为 JavaScript 文件,如下所示:

require('./something')

(并确保'./something' 是从您需要模块的位置到应用程序结构中模块所在位置的路径,或使用绝对路径)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2015-02-14
    • 2021-03-22
    相关资源
    最近更新 更多