knite
knite

Reputation: 6171

Import functions from module to global namespace in Coffeescript?

Start with your module, utils.coffee:

exports.foo = ->
exports.bar = ->

Then your main file:

utils = require './utils'
utils.foo()

foo() and bar() are functions you'll be calling frequently, so you:

foo = require('./utils').foo
bar = require('./utils').bar
foo()

This approach works when only a few functions are defined in the module, but becomes messy as the number of functions increases. Is there a way to add all of a module's functions to your app's namespace?

Upvotes: 4

Views: 5796

Answers (6)

tokland
tokland

Reputation: 67890

Use extend (with underscore or any other library that provides it. Write it yourself if necessary):

_(global).extend(require('./utils'))

Upvotes: 11

Alex Feinman
Alex Feinman

Reputation: 5563

How's this:

global[k] = v for k,v of require './utils'

Upvotes: 1

rgbrgb
rgbrgb

Reputation: 1166

If you don't want to use underscore, you could simply do:

var utils = require('./utils')
for (var key in utils)
  global[key] = utils[key]

Upvotes: 6

Alon Valadji
Alon Valadji

Reputation: 628

Another way to exports all modules function to global scope like so: Application Module:

(()->
    Application = @Application = () ->
        if @ instenceof Application
            console.log "CONSTRUCTOR INIT"
    Application::test = () ->
        "TEST"

    Version = @Version = '0.0.0.1'
)()

Main App:

require  './Application'

App = new Appication()
console.log App.test()
console.log Version

Upvotes: 1

Alon Valadji
Alon Valadji

Reputation: 628

something like that is a good approach to my opinion:

utils.coffee

module.exports = 
    foo: ->
        "foo"
    bar: ->
        "bar"

main.coffee

util = require "./util"
console.log util.foo()

Upvotes: 0

Linus Thiel
Linus Thiel

Reputation: 39231

Is there a way to add all of a module's functions to your app's namespace?

No. This is, to my knowledge, the best you can do (using CS' destructuring assignment):

{foo, bar, baz} = require('./utils')

Upvotes: 3

Related Questions