We can create a module in requireJS by giving it a name:
define("name",[dep],function(dep) { // module definition });
or we can create one excluding the name:
define([dep],function(dep) { // module definition });
Which is the better way to create a module? I know RequireJS recommends to avoid assigning module names.
But I want to know in what scenarios we do and do not have to give a module a name. Does this affect usage? What are the pros and cons of each way?
RequireJS loads each dependency as a script tag, using head. appendChild(). RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.
To fix the problem, you must update your JavaScript define methods within RequireJS, according to following documentation: https://requirejs.org/docs/api.html#define. For more in-depth description of how to avoid this and other RequireJS errors, see http://requirejs.org/docs/errors.html#mismatch .
RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.
2 Answers. Show activity on this post. require(["jquery"], function ($) { function doStuff(a, b) { //does some stuff } $('#the-button'). click(function() { doStuff(4, 2); }); });
This is what the requirejs documentation says on the topic of named modules:
These are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.
But let's say you want your module to have a single well-known name that allows always requiring it in the same way from any other module. Do you then need to use the define
call with a name? Not at all. You can use paths
in your configuration:
paths: { 'jquery': 'external/jquery-1.9.1', 'bootstrap': 'external/bootstrap/js/bootstrap.min', 'log4javascript': 'external/log4javascript', 'jquery.bootstrap-growl': 'external/jquery.bootstrap-growl', 'font-awesome': 'external/font-awesome' },
With this configuration, jQuery can be required as "jquery"
, Twitter Bootstrap as "bootstrap"
, etc. The best practice is to leave calling define
with a name to the optimizer.
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