Timo Timo - 25 days ago 9
CoffeeScript Question

How To Access (Named) Modules In RequireJS?

How can I access a (named) module with RequireJS?

Let's say this is my module (sayings/sayings-list.coffee):

define 'saySomething', [], ->
alert 'something'


My main file (main.coffee) looks like this:

require ['sayings/sayings-list'], (sayings) ->
sayings.saySomething()


Now I want to send a variable back and forth! Something like:

require ['sayings/sayings-list'], (sayings) ->
sayings.saySomething(text)


How would this be reflected in my module?

Thanks.

Answer

General rule: you should use anonymous define calls rather than named define calls and let the optimizer (r.js or other optimizer that understand the AMD spec) add names when it optimizes your modules into a bundle. There are rare exceptions to this rule but what you show here is not an exception.

If you must use a named module you should structure it like this:

define 'saySomething', [], -> 
  saySomething: (text) -> alert text

So that it exports a function accessible as saySomething. Note that the module name and the name of the exported function could be different.

Then you must load it using its name:

require ['saySomething'], (sayings) ->
  sayings.saySomething(text)

And you'll have to set your configuration to give a path that maps the name of the module to the file that contains it. This is necessary because by adding the name to the define call, you've decoupled the module name from the file name. So you have to tell RequireJS how to find the module.

require.config
  paths:
    saySomething: "sayings/sayings-list"
Comments