Require.js Made Easy
Require.js is a module loader / dependency handler that allows you to easily define code modules that will only execute once their dependencies exist.
The require site and documentation can be a tad confusing / overcomplex for a new user so I wanted to write a quick tutorial to make require easy to understand.
File Structure
Our example file structure is:
- index.html
- /js
- init.js
- Car.js
- Wheel.js
Include Require
<script src="require.js" data-main="js/init.js"></script>
You'll notice the "data-main" attribute with the value "js/init.js". This data attribute tells require to load that script once require itself has loaded.
This allows you to have a single <script>
tag that loads require.js and also specify a script to load to start your app, all in one tag.
App Entry Point
We've specified to require that we want to load the init.js file on startup so here's the contents of that file:
require(['Car'], function (Car) {
var car = new Car();
car.drive();
});
You'll notice it calls "require()" instead of "define()"... that is because it doesn't provide any output, only describes what modules it needs.
Modules that don't provide anything can use require(). Modules that provide something use define();
Creating a Module
Every file in your app is a module that can require other modules and provide data for other modules that require it.
Let's look at defining a module called Car:
// Define a module with it's dependencies (Wheel)
define(['Wheel'], function (Wheel) {
var Car = function () {
this.wheel1 = new Wheel();
this.wheel2 = new Wheel();
this.wheel3 = new Wheel();
this.wheel4 = new Wheel();
};
Car.prototype.drive = function () {
console.log('Brrroooommm!');
};
return Car;
});
The define call takes an array of modules that this module depends on, in this case the Wheel module, and then passes each module's return value as an argument in the function which is the second parameter.
The function is only called once all the dependencies are loaded.
Here's the Wheel module:
define([], function () {
var Wheel = function () {
this._diameter = 10;
};
return Wheel;
});
That's all!
That should be all you need to setup and use require for your web app!