Home >Web Front-end >JS Tutorial >js modular approach

js modular approach

一个新手
一个新手Original
2017-09-20 09:26:541451browse


CommonJS

  • 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();

AMD specification

  • 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);

CMD specification

  • 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.

ES6 modular approach

//被导入文件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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn