daily-share
daily-share copied to clipboard
export default 和 export 的区别(2020-3-8)
export default 和 export 的区别 (es6相关)
- export 和 export default 都可以导出 模块、函数、文件、常量等
- 可以在其他文件或者模块中通过import + ( 文件 | 函数 | 常量 | 模块) 名字的方式将其导入,以便于能够对其使用
- 在一个文件中或者模块中,export 、import 可以有多个, export default 只有一个
- 通过export 方式导出时, 在导入时需要 加 {} ,export default 则不需要
- export 直接可以导出变量表达式, export default 不可以
export 导出
export function hello() {
console.log('yaogengzhu')
}
export const a = '测试常量'
export const b = 1
import 引入
import {hello, a , b} from './对应文件名'
export default 默认导出只能是一个
const a = 1
export default a
export default 引入
import a from '../'
- require: node 支持的引入
- export/ import 只有es6支持的导出引入
- module.exports / exports 只有node支持的导出
补充 exports 和 module.exports (node支持的导入方式)
node模块中遵循的是commonJS规范。
commonJS 定义的模块分为
- 模块标识(module)
- 模块定义(exports)
- 模块引用(require)
exports
和 module.exports
在一个node 执行文件时,会给这个文件内生成一个exports
和 module
对象。
而module
有一个exports
属性,他们都指向一块 {} 内存区域中
exports = module.exports = {}
// 仔细操作一番
let a = 2
console.log(exports) // {}
console.log(module.exports) // {}
exports.a = 10
console.log(exports) // { a: 10 )
console.log(module.exports) // { a: 10 }
const a = require('./sum.js')
console.log(a)
// { a: 2, hello: [Function] }
总结
require
引入的内容其实就是module.exports
指向的内存的块内容,并不是exports的,简单的来说呢, 区分他们就是exports
就是module.exports
的引用,辅助module.exports
添加内容用的。 在使用的时候尽量使用module.exports
导出,然后使用require
引入