Is there any way to access all loaded modules of require.js?
Background:
I want to automatically call an init()
function of my javascript-modules after all of them are loaded, see require.js + backbone.js: How to structure modules that have an initialize function? Without require.js I looped over my own module-storage and called each init()
function.
I now want to do this with require.js. I'm aware that calling a my_custom_init_function_favoritecolor_petname_love123
of every loaded module (including external libraries) is dangerous. I hope that this will cause less trouble than manually keeping a list of all modules (and the requirements of these modules) up-to-date. Forgetting one module init() is much more likely than a third-party library having my custom function name (though the latter is probably harder to debug).
Or does anyone have a better idea of how to accomplish that?
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
“Require” is built-in with NodeJSWith require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module. exports .
Now, I personally find it better to declare all your modules on the top of the file since it: Makes it easier to know when you are requiring a module that has a bug (for example, crashes something) Makes it easier for the reader to know all the dependencies of your module.
To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.
Yes, require.s.contexts._.defined
is an object which its keys are the module names and the values include the value returned from that module.
require.s.contexts._.defined
includes all the modules (either define()
or require()
such as the Javascript file that is the starting point of the program and is indicated using data-main
for RequireJS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With