Is it possible to require code from another plugin in your plugin?
-
I'd like to call functionality from an existing plugin from my plugin. Is there a way to refer to the code in other plugins with something similar to this:
require.main.require('./src/plugins/nodebb-plugin-name/lib/filename.js');
-
Thank you @baris !
-
lol, of course it would be the filesystem path. Years of java has damaged me
-
I think it's better to use
require('nodebb-plugin-name/lib/filename.js')
(see node.js docs) rather thanrequire.main.require('./node_modules/...')
in this case
Try avoiding the use ofnode_modules
anywhere in your code -
@frissdiegurke Thanks! That makes sense and works well with one caveat. It looks like from a plugin that you need to refer to the main module loader (is that the right terminology?) like so:
require.main.require('nodebb-plugin-pluginname/lib/modulename');
-
@jongarrison Yes, you'd need the
require.main
to require from the NodeBB context. -
I've used
plugins.libraries['pluginid'].function()
to do this. Are there any caveats to using this method? Other than the plugin needing to actually be enabled. -
@yariplus The plugin needs to export the method you want to use within the main script. Using any of the ways above, you can use exports of non-main modules within that plugin.
Checking whether any plugin is enabled or not would be a task to check via NodeBB modules. Directly attempting to access a plugins exports however should not depend on the internal structure of NodeBB in my opinion.
If you want to call a plugins exported attributes only iff the plugin is enabled, your way seems to be good though.
I guess I'd still use// would be neat if NodeBB provides a function for this ;-) Accessing NodeBB's non-function attributes directly seems somehow wrong to me // proposal: plugins.isEnabled("my-plugin") if nothing alike exists already if (plugins.libraries.hasOwnProperty("my-plugin")) { require("my-plugin").function(); }
since it clearly states where the functions source code lies.