RequireJS is a JavaScript file and module loader. It can be used in browsers and other javascript environments like Node. This article is intended as a quickstart guide for requirejs for beginners with some comments on when it can be used.
Requirejs example
Here is a simple example using requirejs:
<!DOCTYPE html> <html> <head> <title>RequireJS basic example</title> <script src="/demo2/requirejs-example/require.js"></script> <script> requirejs.config({ //By default load any module from here baseUrl: '/demo2/requirejs-example' }); </script> </head> <body> <h1>RequireJS basic example</h1> <div id="data1"></div> <script type="text/javascript"> require(["foo"], function (foo) { document.getElementById("data1").innerHTML = "foo.key1=" + foo['key1']; console.log("foo=%o", foo); }); </script> </body> </html>
Here is the foo.js code used in above example:
define({ key1: "val1", key2: "val2" });
Few points to note:
- Requirejs needs modules to be declared using define.
define
is a function defined in require.js source.- Require is used to load additional modules.
- Both define and require can specify dependencies.
Requirejs base directory
The base-dir can be set in three ways in requirejs:
- Implicitly set to current directory of the page is nothing is specified.
- If data-main attribute is specified as shown below, then the directory of main js becomes base-dir.
<script data-main="js/app.js" src="js/require.js"></script>
- Using requirejs.config (our example used this) as shown below:
requirejs.config({ //By default load any module IDs from js/lib baseUrl: 'js/lib' });
Requirejs – using shim for “browser globals” scripts
Require can also be to configure the dependencies and exports for traditional “browser globals” scripts that do not use define() to declare the dependencies and set a module value. Here is an example:
requirejs.config({ shim: { 'bar' : { // These script dependencies should be loaded before loading bar.js // deps: ['dep1', 'dep2'], // Once loaded, use the global 'Bar' as the module value. exports: 'Bar' } } })Once this is done, regular require call can be used for javascript file bar.js as shown below:
require(["bar"], function(Bar) { // do something... });Here is sample bar.js code
var Bar = function () { this.key3 = "val3"; this.key4 = "val4"; };
Requirejs – additional comments
- For detailed official documentation visit requirejs site.
- Requirejs seems more suitable when project is big and there are too many dependencies.
- It is also handy util for loading multiple scripts and doing a callback once all the scripts are loaded.
- For simple projects requirejs does not seem to be that useful.
- Requirejs needs each module to be in its own file. But in production you may want to combine multiple javascript files. You may want to look at requirejs optimization to achieve this.