commonJs 规范 与 AMD 规范

参考:http://javascript.ruanyifeng.com/nodejs/module.html#toc4

          http://javascript.ruanyifeng.com/tool/requirejs.html 

          https://blog.csdn.net/crystal6918/article/details/74906757/

commonJs 规范

同步应用

模块定义:exports   module.exports

 

var x = 5;
var addX = function (value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

模块引用:  require

var example = require('./example.js');

console.log(example.x); // 5
console.log(example.addX(1)); // 6

与AMD规范的兼容性

define(function (require, exports, module){
  var someModule = require("someModule");
  var anotherModule = require("anotherModule");

  someModule.doTehAwesome();
  anotherModule.doMoarAwesome();

  exports.asplode = function (){
    someModule.doTehAwesome();
    anotherModule.doMoarAwesome();
  };
});

 

 AMD 规范

异步模块引用

模块定义:define

1.独立模块定义

define(function () {
	return {
	    method1: function() {},
		method2: function() {},
    };
});
 

2.非独立模块定义  

define(['module1', 'module2'], function(m1, m2) {
 //module1  module2  依赖的模块    m1,m2  分别对应module1  与 module2
    return {
        method: function() {
            m1.methodA();
			m2.methodB();
        }
    };

})

 

模块引用:require 

require(['foo', 'bar'], function ( foo, bar ) {
        foo.doSomething();
});

最后就是ES6 moduel

模块定义:export 

//导出变量
export var color = "red";
export let name = "cz";
export const age = 25;

//导出函数
export function add(num1,num2){
    return num1+num2;
}

//导出类
export class Rectangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
    }
}

function multiply(num1, num2) {
    return num1 * num2;
}

//导出对象,即导出引用
export {multiply}

 模块引用    import

import { identifier1,identifier2 } from "./example.js"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值