commonJS规范下的export和es6的其实差别还是有一点的,话不多话,专门总结了下面的各种写法。
1.commonJS的exports和require的用法
## 第一种:
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();