Perfect way for requiring NodeBB modules?
-
So what is the absolute best way to go around doing this?
Doing something like
module.require('../../etc')
will breaknpm link
. This lead to the use ofmodule.parent.require('stuff')
, which seems to work fine.However, pretend I have the following situation:
- Plugin root
- library.js -
module.parent
works fine here - lib
- submoduleA.js - this is
require
'd from library.js.module.parent
refers to library.js,module.parent.parent
is necessary. - submoduleB.js - this is
require
'd from submoduleA.js,module.parent.parent.parent
is necessary to access NodeBB modules.
- submoduleA.js - this is
So what would be the best way to go from here to keep things sane and clean?
-
Can't say I ever encountered that specific use case, @mr_waffle
module.parent.require works great for the case you described above, as outlined in my blog post. In your case, you might want to pass in the library instead, if that helps keep things tidy for you:
library.js
var Posts = module.parent.require('./posts') , submoduleA = require('./submoduleA')(Posts);
submoduleA.js
module.exports = function(Posts) { var submoduleB = require('./submoduleB')(Posts); };
submoduleB.js
module.exports = function(Posts) { // Do stuff with Posts here };
-
To get back on this, I have currently solved it in the following way:
###/lib/nodebb.js:module.exports = { "Meta": module.parent.parent.require('./meta'), "User": module.parent.parent.require('./user'), "Plugins": module.parent.parent.require('./plugins'), "SocketIndex": module.parent.parent.require('./socket.io/index'), "ModulesSockets": module.parent.parent.require('./socket.io/modules'), "db": module.parent.parent.require('./database') }
###library.js:
var NodeBB = require('./lib/nodebb');
###/lib/submoduleX.js:
var NodeBB = module.require('./nodebb'), db = NodeBB.db, User = NodeBB.User, Plugins = NodeBB.Plugins;
##Why this works
I read somewhere thatrequire
caches the files you load. That means that if require mynodebb.js
fromlibrary.js
, I can later loadnodebb.js
from any submodule I want and it will work.