Home > Article > Web Front-end > js modular approach
In CommonJS, there is a global method require() for loading modules. exports is used to export modules.
方法一://被导入文件aa.jsmodule.exports = function() { alert('a'); };//主文件main.jsvar aa = require('./aa.js'); aa(); 方法二: //被导入文件aa.jsmodule.exports = { a:function(){ alert('a'); }, b:function(){ alert('b'); } }//主文件main.js var greeter = require('./aa.js'); greeter.a(); greeter.b();
Since the browser-side module cannot be loaded synchronously, it will affect the loading execution of subsequent modules, so the AMD specification born. Suitable for asynchronous loading of modules in a browser environment.
Import method: require([module], callback);
Export method: define(id, [depends], callback);
The CMD specification is very similar to AMD, trying to keep it as simple as possible, and keeping a close relationship with the Modules specification of CommonJS and Node.js Great compatibility.
//被导入文件a.jsexport function bbb(){ alert('bbb'); } export function ccc(){ alert('ccc'); } export function ddd(){ alert('ddd'); }//主文件main.jsimport * as b from './b.js';//导入所有内容import {bbb,ccc} from './b.js';//只导入需要的函数
The above is the detailed content of js modular approach. For more information, please follow other related articles on the PHP Chinese website!