Basic usage of requireJS
RequireJS is a JavaScript module loader that allows modules to be asynchronously loaded in the browser. It helps developers better manage dependencies between modules and provides a modular development approach.
Here is the basic usage of RequireJS:
- Introduce the RequireJS library.
Include the RequireJS library in the HTML file.
<script src="require.js"></script>
- Module definition
Define a module using the define function.
// math.js
define(function() {
var add = function(a, b) {
return a + b;
};
var subtract = function(a, b) {
return a - b;
};
return {
add: add,
subtract: subtract
};
});
- Load module
Load the module using the require function.
require(['math'], function(math) {
var result = math.add(1, 2);
console.log(result); // 输出3
});
Specify the modules to be loaded in the first argument of the require function, and use the second argument as a callback function which will be called once all the modules are loaded.
- Set module path
You can use the require.config function to configure the paths and aliases of modules.
require.config({
baseUrl: 'js', // 模块路径的基准目录
paths: {
'jquery': 'jquery.min' // 定义别名,使得可以使用`jquery`代替`jquery.min`
}
});
Then, you can directly use the alias to load modules in the require function.
require(['jquery'], function($) {
$('body').text('Hello RequireJS');
});
The above is the basic usage of RequireJS, which can help developers better organize and manage modular JavaScript code.