export部分和全部导出,import部分和全部导入

2,494 阅读1分钟

1.export部分导出, import部分导入


// A.js

export const name = "test"

export function helloWorld(){

    console.log('helloworld')
    
}

import { name, helloWorld } from './A.js'

或者分开写:

import { name } from './A.js'

import { helloWorld } from './A.js'
或者使用 module 关键字 整体导入
module a from './A.js'
使用:
a.name
a.helloWorlld
  1. export全部导出, import 全部导入
const name = "test"
function helloWorld(){
    console.log('helloworld') 
}
export { name, helloWorld } 

import A from './A.js'

或者 import * as A from './A.js'

A.name
A.helloWorld()

如果使用全部导出,则必须使用全部导入。建议使用部分导出,把选择权交给使用者。

3.export 与 export default

export导出时,import 必须使用 {}。

export default 只能输出一次, import 导入时不需要 {},且可以自己随便定义一个名字来接受对象。

补充: export和import 的复合写法

在开发中,我们一般需要模块化编程,这就用到export和import的组合使用

export { default as CommanAPI } from './modules/common'

上面的代码等同于:
import { CommonAPI }from './mudules/common'
export default CommonAPI;