superlukas
superlukas

Reputation: 491

Can't require local CoffeeScript modules

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)

Upvotes: 3

Views: 4867

Answers (5)

pcv
pcv

Reputation: 2181

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

Upvotes: 0

random-forest-cat
random-forest-cat

Reputation: 35884

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

Upvotes: 0

Stephen Henderson
Stephen Henderson

Reputation: 2711

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.

Upvotes: 13

superlukas
superlukas

Reputation: 491

brew reinstall node did the trick. Not sure why.

Upvotes: 0

Alex Netkachov
Alex Netkachov

Reputation: 13522

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.

Upvotes: 1

Related Questions