2

I was wondering if you are able to require a coffeescript from within another coffeescript.

My example code from file "user.coffee"

class UserObj
    constructor: (@name) ->
        console.log @name

My example code from main file

require "./user.coffee"

User = new UserObj "Example"

Is this possible from within a coffeescript file or just a js file?

1

1 Answer 1

8

Yes it is possible.

user.coffee:

exports.UserObj = 
class UserObj
    constructor: (@name) ->
        console.log @name

main.coffee:

{UserObj} = require "./user"

User = new UserObj "Example"
Sign up to request clarification or add additional context in comments.

4 Comments

But this is just for Node right? I thought CoffeeScript may have pull together the required files on compilation of main.js
@ThomasWelton That's just for Node. Currently CoffeeScript compiler is just a file-to-file transcompiler, it doesn't do any project structure analysis and because of that no aggregation. There may be other tools approaching the issue. I even remember writing one myself.
Thanks. I later went on to use requirejs which I'm very happy with for loading coffeescript modules and classes.
If you are using a single class per file, then I would prefer module.exports = UserObj, now the prototype is exposed out of the file, and the {UserObj} = require './user' isn't necessary. The loading of the constructor would simply be: UserObj = require './user'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.