export、exports、modules.exports 和 require 、import你是否有些凌乱

353 阅读1分钟

export、exports、modules.exports 和 require 、import在使用中有时候总是有些混乱,今天就特地来记录一下它们的区别。 1.功能区别


引用功能:require、import
导出功能:export、exports、module.exports
其中Nodejs不支持import和export
import、export、export default为es6支持的导入导出 exports、module.exports为nodejs支持的导出

2.es6中import、export、export default的使用

export可以输出单个变量、多个变量,可以输出函数以及别名。
import和export配套使用,可以导入变量和别名。需要注意导入的变量名和导出的变量名需要爆出一致,导入from后面跟的相对路径和绝对路径都可以,.js文件后缀也可以省略。
as前是原名,as后是别名

// export导出的第一种写法
export const a = () => 'testA'
export const b = () => 'testB'
export function c() {
   ...
}

// export导出的第二种写法
const a = () => 'testA'
const b = () => 'testB'
function setName() {
   ...
}
export { a, b, setName as c }

// export对应import的用法
import { a, b , c as setName } from 'xxx'  //注意有大括号

// export default导出上面两个方法的写法
export default {
    a: () => 'textA',
    b: () => 'textB'
}

//export default对应import的写法
import test from 'xxx.js'  //注意没有大括号
  • 一个模块中智能有一个export default默认输出

3.nodejs中exports、module.exports和require的使用

// module.exports的使用
var test = {
    name: 'xiaoming',
    sayName: function() {
        console.log(this.name)
    }
}
module.exports = test

// exports的使用
var test = {
    name: 'xiaoming',
    sayName: function() {
        console.log(this.name)
    }
}
exports.sayName = test.sayName

// require的使用
let abc = require('xxx.js')

两者主要区别有:
1.exports其实是modeule.exports的引用。所以不能在使用了exports.xxx后,再改变module.exports的指向。

var module = new Module()
var exports = module.exports

2.对于要导出的属性,可以直接挂到exports对象上。
3.需要将模块定义为一个类时,使用module.exports