Requiring CoffeeScript file from within another CoffeeScript file with nodejs
13,488
Yes it is possible.
user.coffee:
exports.UserObj =
class UserObj
constructor: (@name) ->
console.log @name
main.coffee:
{UserObj} = require "./user"
User = new UserObj "Example"
Author by
user1302818
Updated on June 14, 2022Comments
-
user1302818 almost 2 years
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?
-
Thomas Welton over 11 yearsBut this is just for Node right? I thought CoffeeScript may have pull together the required files on compilation of main.js
-
Nikita Volkov over 11 years@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.
-
Thomas Welton over 11 yearsThanks. I later went on to use requirejs which I'm very happy with for loading coffeescript modules and classes.
-
thetrompf about 11 yearsIf 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'