Can't require local CoffeeScript modules

2020-07-23 05:43发布

I'm running Node.js 0.10.21. I tried both CoffeeScript 1.6.3 and master both with and without require('coffee-script/extensions'). Compiling the two files to JavaScript and running them directly in Node works just fine of course.

# ./folder/a.coffee
require('../b').test()

# ./b.coffee
exports.test = -> console.log 'yay'

# $ coffee folder/a.coffee
#
# Error: Cannot find module '../b'
#   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> (/Users/test/folder/a.coffee:1:1)
#   at Module._compile (module.js:456:26)

5条回答
聊天终结者
2楼-- · 2020-07-23 06:26

You do not need to reinstall node. Just add coffee-script as a dependency

npm install --save-dev coffee-script
node -v # v0.10.31
查看更多
beautiful°
3楼-- · 2020-07-23 06:33

Watch out for the paths, they're relative to the script you're running, not your current folder. So if you run

coffee folder/a.coffee

and your module is in folder, you need to require ./b.coffee not ./folder/b.coffee

查看更多
爷的心禁止访问
4楼-- · 2020-07-23 06:34

I found this SO question while trying to solve this problem for CoffeeScript version 1.7.1. It doesn't apply to the OP's version 1.6.3 but it may help others with this problem in 2014 and later.

The solution is to either:

 var foo = require('coffee-script/register');
 foo.register();

or, you can simply do this (which is my usual preference):

 require('coffee-script/register');

What's happening is that for CoffeeScript 1.7, a breaking change was introduced.

It solves for cases where a variety of coffee-script versions are used within the set of dependencies that you may be loading or that your dependencies are loading.

The idea is that any particular module (or sub-module) should be able to be compiled by the version of coffee-script that it is compatible with.

Read about that here: https://github.com/jashkenas/coffee-script/pull/3279.

查看更多
【Aperson】
5楼-- · 2020-07-23 06:36

Being recreated on my computer the coffee folder/a.coffee works perfectly fine.

I think that adding './' at the beginning of the require in the file a.coffee may help:

require('./../b').test()

You may also try to require the files by the absolute paths, just to check that they are accessible.

查看更多
再贱就再见
6楼-- · 2020-07-23 06:40

brew reinstall node did the trick. Not sure why.

查看更多
登录 后发表回答