Import functions from module into 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 that you often call, so you:

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

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

+4
source share
6 answers

Is there a way to add all the module functions to the application namespace?

Not. This, to my knowledge, is the best you can do (using CS destruction assignment ):

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

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

 _(global).extend(require('./utils')) 
+11
source

If you do not want to use underscore, you can simply do:

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

Another way to export all modules to the global area: Application module:

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

Main application:

 require './Application' App = new Appication() console.log App.test() console.log Version 
+1
source

Like this:

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

something like this is a good approach to my opinion:

utils.coffee

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

main.coffee

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

Source: https://habr.com/ru/post/1396234/


All Articles