4

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?

6 Answers 6

11

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

_(global).extend(require('./utils'))
Sign up to request clarification or add additional context in comments.

Comments

6

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]

2 Comments

Not bad! I wish Coffeescript had an equivalent to the Python one-liner "import * from bar".
@knife it's one line, though not a one liner: global[k] = v for k,v of require './utils'
3

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')

Comments

1

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

1 Comment

Interesting idea! I'm going to try this for a bit before marking the answer as correct.
1

How's this:

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

Comments

0

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()

2 Comments

I think the OP asked for a way to import all functions from a module, not how to export all functions in a module. The advice is useful, though.
Yes, I think you're right. I've added another Answer below :)

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.