commonJS的require/exports和Es6的exports/import的写法

1.commonJS的require/exports

 第一种:
exports.say = function(){ }
exports.hello = function(){}
或者这种写法
function say() {}
function hello() {}
exports.say = say
exports.hello = hello
// 调用
var user = require('./user.js')
user.say()
user.hello()
 
 第二种:

module.exports.say = function () {}
module.exports.hello = function () {}
// 调用
var user = require('./user.js')
user.say()
user.hello()
 
第三种:

module.exports = {
    name: '小明',
    say: function () {}
    hello: function() {}
}
// 调用
var user = require('./user.js')
user.say()
user.hello()
console.log(user.name)


2.ES6的export和import用法

第一种:
export function say() {}
export function hello() {}
// 调用
import {say,hello} from './user.js'
say();
hello();
 
第二种:
function say() {}
function hello(){}
export { say, hello }
// 调用
import {say,hello} from './user.js'
say();
hello();
 
第三种:
function say() {}
function hello() {}
// 导出的时候可以起一个别名
export {
    say as method1,
    hello as method2
}
// 调用
// 这里已经是需要用到导出的
import {method1,method2} from './user.js'
method1();
method2();
 
// 或者导入的时候也是可以起一个别名的,并且两边同时都是存在别名也不会有影响
import {method1 as aa,method2 as bb} from './user.js'
aa();
bb();
 
第四种:

export default function () {}
// 调用,因为是default导出的,所以调用的时候可随便起名字
import say from './user.js'
say();
 
第五种:
export default {
    name: '小明',
    say: function () {}
}
// 调用
import hello from './user.js'
console.log(hello.name);
hello.say();
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值