Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
knite Avatar asked Nov 29 '22 03:11

knite


2 Answers

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

_(global).extend(require('./utils'))
like image 54
tokland Avatar answered Dec 05 '22 21:12

tokland


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]
like image 31
rgbrgb Avatar answered Dec 05 '22 21:12

rgbrgb