默认导出和具名导出

178 阅读1分钟

1.默认导出(export default)

  • 一个模块只能有一个默认导出
  • 导入时可以使用任意名称
  • 通常用于导出模块的主要功能或值
导出
// module.js
const mainFunction = () => {
  console.log("hello")
};
export default mainFunction
导入
// app.js
import myFunction from './module.js' // 名称可以任意
myFunction()

2.具名导出(export)

  • 一个模块可以有多个具名导出
  • 导入时需要与导出相同的名称
  • 通常用于导出多个辅助功能或值
导出
// module.js
export const functionA = () => {
  console.log("This is function A")
}

export const functionB = () => {
  console.log("This is function B")
}
导入
// app.js
import { functionA, functionB } from './module.js' // 名称必须一致
functionA()
functionB()
使用别名
import { functionA as foo, functionB as bar } from './module.js'
foo()
bar()

3.同时使用默认导出和具名导出

  • 一个模块可以同时使用默认导出和具名导出
导出
// module.js
const mainFunction = () => {
  console.log("This is the default export")
}

export const helperFunction = () => {
  console.log("This is a named export")
}

export default mainFunction
导入
// app.js
import mainFunction, { helperFunction } from './module.js'
mainFunction()
helperFunction()

4.总结对比

对比.png