Home >Web Front-end >JS Tutorial >Detailed examples of CommonJS
1. CommonJS
is used for server-side modular programming. For example, nodejs adopts this specification;
A file is a module , the require method is used to load modules. This method reads a file and executes it, and finally returns the module.exports object inside the file;
require reads .js files by default, so require (module name) does not need to be written with a suffix;
is loaded synchronously. Since the modules loaded on the server side are generally local, this is OK; but on the client side, if a module is too large, Will cause the page to "fake death";
The module.exports attribute represents the external output interface of the current module. When other files load the module, they actually read the module.exports variable; for convenience, You can use exports, exports points to module.exports; that is, exports = module.exports = {}
exports.xxx is equivalent to adding an attribute to the exported object, which is visible to the calling module ;
exports = is equivalent to reassigning exports, which cuts off the association with module.exports, and the calling module cannot access the exports object and its properties;
2. AMD
Load module: require([module], function(module){});
Define module: define([module], function(module){}); module is a dependent module;
require.config({ baseUrl: "js/lib", paths: {"jquery": "jquery.min", "underscore": "underscore.min", "backbone": "backbone.min" }, shim: {'underscore':{ exports: '_' }, 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' } } }); // exports值(输出的变量名),表明这个模块外部调用时的名称;deps数组,表明该模块的依赖性
define(function(require, exports, module){ var a = require('a'); a.foo(); };
The above is the detailed content of Detailed examples of CommonJS. For more information, please follow other related articles on the PHP Chinese website!