common.js和ES6的 模块的暴露与接收

commom.js:

module.exports是当前模块对外输出的接口

a.js:

module.exports.fn=function(){...}

b.js:

var a=require('./a.js')
a.fn()

exports是module.exports的引用,单纯的指向module.exports的内存中的值,即exports=module.exports={},故可以使用exports代替module.exports,但是不是很建议这样做,使用module.exports更安全,出错几率小。

ES6:

1.export可以选择性地给其他模块暴露(提供)自己的属性和方法,供其他模块使用。

a.js:

export var a='hello';
export function fn(){...}

//或者这样写:
var a='hello';
function fn(){...}
export {a,fn}

b.js:

import {a,fn} from './a.js';
console.log(a);
fn();

必须用{}包住变量名,并且导入的变量名要和暴露的变量名一致。

2.export default 指默认暴露,一个文件只能有一个:

a.js:

var a='hello';
function fn(){...}
export default {a,fn}

b.js:

import msg from './a.js';
console.log(msg.a);
msg.fn();

不用{}包住,msg指项暴露的对象,msg可以任意取名字。

参考:传送门 (非常详细的介绍)

猜你喜欢

转载自blog.csdn.net/bamboozjy/article/details/81305072