satyajit
satyajit

Reputation: 1570

How to import files from other coffeescript files

I am trying avoid duplicate import statements in my coffeescript files.

Say I need to import from these three files in all my *.coffee

#import "../node_modules/moment/moment.js"
#import "../testhelpers.js"
#import "../tuneup/tuneup.js"

How can I avoid code duplication? I tried

  1. Creating a separate helper coffee file and importing it
  2. Creating a separate helper JS file and importing it

But both didn't work.

This is not a web application, so size of javascript and unnecessary loading of JS isn't a concern.

Upvotes: 1

Views: 7258

Answers (1)

Sanketh Katta
Sanketh Katta

Reputation: 6311

If you are using node.js, you use require:

moment = require "../node_modules/moment/moment.js"
testhelpers = require "../testhelpers.js"
tuneup = require "../tuneup/tuneup.js"

In addition, you will need to use the exports object in the files you are importing.

For example in moment.js:

exports.somefunc = (foo) -> console.log(foo)

Then, when you import:

moment = require "../node_modules/moment/moment.js"
moment.somefunc("hello world")

Anything not bound to exports will not be accessible when you call require.

Upvotes: 1

Related Questions