JS模块导入导出规范-CommonJS | ES6 -规范案例

module.exports、exports和export、export default

总体上区分两大规范 CommonJS模块规范和ES6模块规范
require: node 和 es6 都支持的引入
export / import : 只有es6 支持的导出引入
module.exports / exports: 只有 node 支持的导出

Node里面的模块系统遵循的是CommonJS规范。
CommonJS定义的模块分为: 模块标识(module)、模块定义(exports) 、模块引用(require)

1.module.exports 和exports 是Commonjs的规范
2.export 和export default 是es6 规范
3.require 是amd规范引入方式
4.import 是es6 的一个语法标准

module.exports 、exports

 module 变量代表当前模块,这是个对象,会创建exports的属性,属性的默认值是空对象

//导出使用方法:
function add(a,b) {
    return a+b;
}
var a1 = 1
module.exports = {add,a1};
module.exports = {a:1};
module.exports.a = 1
module.exports = function(name,age,money) {
    this.name = name;
    this.age = age;
    this.money = money;
    this.say = function() {
      console.log(123)
    }
  };
 
//导入使用方法
var req = require ('../app.js');
console.log(req.a1,req.a)
const {add,a1} = require('../app.js')

exports 是module.exports的一个引用,可以认为是 var exports = module.exports

exports.a = 1;
exports.add = add
//导入使用方法
var req = require ('../app.js');
console.log(req.a)

module.exports 、exports区别

  1. 相对而已,exports不能导出匿名函数(比如没有变量名的函数)也不能写 exports = {acc};
  2. exports是引用 module.exports的值。module.exports 被改变的时候,exports不会被改变,而模块导出的时候,真正导出的执行是module.exports,而不是exports。
  3. Require 引入模块后,放回给调用者的是module.exports 而不是exports
module.exports = {name: '叔叔'};
exports = {name: '阿姨'}
//main.js
let people = require('./people');
console.log(people);//输出:{name: '叔叔'}

export、export default

 export default导出

var name = 'javk'
var sys = function () {
    console.log('test')
}
var name1;
//一个模块文件只能有一个export default,下面是举例而已
export default { name , sys}
export default const name3 = 'error'; //这个是错误的,可以用下一行这种方式
export default name1 = 'marry'
export default { name2: 'bob'} //暴露一个对象
export default  function() {
    console.log ('export 不能这样子')
}

//引入
import test form 'app.js' // test可以随便取名字,不需要花括号

export 导出

export {age,open} //等同于下边
export {age}
export {open}
export const age1 = 23 //let 也行
 
export class User {
    constructor(name) {
      this.name = name;
    }
  }
  export function log(sth) { //不能没有函数名字
    return sth;
}
 
//导入方法 对应导入的变量或函数,一定要花括号
import {age,open} form "app.js" // 花括号里面的值必须和暴露的变量相同
import {age1 as age2} form "app.js"
import * as test form "app.js"

 export、export default 区别

  1. export default 在一个模块中只能有一个,也可以没有,export可以有很多个
  2. export default 的对象、变量、函数、类、 可以没有名字,但export导出的必须有名字
  3. 两者导出,用import导入对应会有区别。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieDYH

谢谢您嘞!我会继续加油地

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值