If you
require()
a module there are a couple simple rules:- you don't need to put the '.js' on the end of the file.
- if you
require('./my_module')
the file must be in
- ./my_module.js or
- ./my_module/index.js
- if you
require('my_module')
the file must be in
- ./node_modules/my_module.js or
- ./node_modules/my_module/index.js or
- or a node_modules directory toward root (.. or ../.. or ../../.. till /node_modules)
As for the module file itself, you must set the object to be returned from the
require()
call. This is the part that flummoxed me.It is simple, in your module there is a module variable automagically. That module variable points to an object that is pre-populated with many properties. Just do a
console.dir(module)
in your empty module file to see it all.The object that gets returned from the
require()
call is pre-allocated in the module.exports property. There is also a variable called exports that contains the very same object that is in module.exports. If you assign a new object to the exports variable, eg exports = {};
, that new object will NOT be exported as it is not the same object that is in module.exports. Think of it as if there is a invisible exports = module.exports = {};
line at the beginning of your module. The exports variable is only there for your convenience and only the object pointed at by module.exports matters.This is simple and I found no one who said it straight out. There was crap about exports being an "alias" for module.exports and other balderdash. If you want to create your own elaborate exported object just do this:
exports = module.exports = { ... my big-ass exported object ... };