RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
From RequireJS
Third-Party libraries sometimes come without AMD version. This post introduces a method to wrap them using shim. I’m going to take Three.js as example. The file structure is shown below. three.js
and three.EdgeShader.js
are required in A.js
, and the later of which depends on the former one.
index.html
/vendor
three.js
three.EdgeShader.js
/src
/js
A.js
In index.html
, we use shim for three
and threeEdge
. The deps
attribute of threeEdge
denotes the dependence on three
, and exports
makes THREE
and THREE.EdgeShader
accessible elsewhere.
require.config({
baseUrl: './src/js',
paths: {
'three': '../../vendor/three',
'threeEdge': '../../vendor/three.EdgeShader',
},
shim: {
'three': {
exports: 'THREE'
},
'threeEdge': {
deps: ['three'],
exports: 'THREE.EdgeShader'
}
}
});
In A.js
, they can be accessed by calling require('three')
and require('threeEdge')
.
var THREE = require('three');
THREE.EdgeShader = require('threeEdge');