Basically, how do I use require?


#1

Yes, sigh, I’m dumb.

leedohm said, in Why require is slow?:

When the code is executed, what is returned to the script that called it? How can I use a class that I wrote in a seperate file? I tried using a return call, but it didn’t return anything different. No matter what I do, it just returns Object {}


#2

To my understanding, the module system in Node (which is where the require stuff comes from) returns whatever you supply to module.exports. For example, most of the modules in my Atom packages follow the pattern:

class Foo
  something: (somethingElse) ->
    # Do something cool ...

module.exports = Foo

This allows me to import the class Foo someplace else by doing:

Foo = require './foo'

But you aren’t limited to exporting classes, you can export functions:

module.exports = (param) ->
  # Do something cool

Which can then be used by:

foo = require './foo'

foo('magic')

Or objects or whatever you can think of. Because a module can export whatever you like, you have to be careful to match up the calling protocol with the exporting protocol. Mismatches can be frustrating and, in my experience, hard to debug :laughing:

You can even reference module.exports multiple times like here:

Though, really the first reference on line 7 exports an object which is then amended on lines 24 and 25. So you’re really still only exporting one thing, an object.


#3

You can also just export things without using modules.exports

# file mod1.coffee
exports.func1 = -> 1
exports.func2 = -> 2

and then require that module …

mod1 = require 'mod1'
console.log mod1.func1()  # gives 1
console.log mod1.func2()  # gives 2

In the module, exports is actually module.exports, but be careful. You can’t just replace exports like …

exports = class foo  # doesn't work
module.exports = class Foo  # works