版权声明:转载或者引用请标明来源! https://blog.csdn.net/qq575792372/article/details/87631582
commonJS规范下的export和es6的其实差别还是有一点的,话不多话,专门总结了下面的各种写法。
1.commonJS的exports和require的用法
第一种:
exports.say = function(){ }
或者
function say() {}
exports.say = say;
// 调用
var hello = require('./hello.js')
hello.say();
第二种:
module.exports.say = function () {}
// 调用
var hello = require('./hello.js')
hello.say()
第三种:
module.exports = {
name: '小明',
say: function () {}
}
// 调用
var hello = require('./hello.js')
hello.say()
console.log(hello.name)
2.ES6的export和import用法
第一种:
export function say() {}
export function hello() {}
// 调用
import {say,hello} from './hello.js'
say();
hello();
第二种:
function say() {}
function hello(){}
export { say, hello }
// 调用
import {say,hello} from './hello.js'
say();
hello();
第三种:
function say() {}
function hello() {}
// 导出的时候可以起一个别名
export {
say as method1,
hello as method2
}
// 调用
// 这里已经是需要用到导出的
import {method1,method2} from './hello.js'
method1();
method2();
// 或者导入的时候也是可以起一个别名的,并且两边同时都是存在别名也不会有影响
import {method1 as aa,method2 as bb} from './hello.js'
aa();
bb();
第四种:
export default function () {}
// 调用,因为是default导出的,所以调用的时候可随便起名字
import say from './hello.js'
say();
第五种:
export default {
name: '小明',
say: function () {}
}
// 调用
import hello from './hello.js'
console.log(hello.name);
hello.say();