从另一个文件导出所有常量

时间:2018-11-17 10:39:29

标签: javascript ecmascript-6

我想创建index.js文件,该文件将导出所有常量和来自另一个文件的默认导出。例如:

userActions.js

export const login = (username, password) => { ... }
export const logout = () => { ... }

User.js

export default class User { ... }

Book.js

export default class Book { ... }

index.js

import { login, logout } from './userActions'
import Book from './Book'
import User from './User'

export { login, logout, Book, User }

然后,在任何文件中都可能出现这种情况:

import { login, Book, User } from './index.js'

不幸的是,我经常添加新的用户操作,并且我不想每次都更改index.js。所以我想在 index.js 中使用它:

export * from './userActions'

另一个文件中的某处(一切正常)...

import * as allExports from './index.js'
console.log(allExports) // { login: ƒ, logout: ƒ, __esModule: true }

但是如果我将默认出口添加到命名出口( index.js ):

import Book from './Book'
import User from './User'
export * from './userActions'
export { Book, User }

只有第一个默认导出(在另一个文件中的某个位置):

import * as allExports from './index.js'
console.log(allExports) // { Book: f, __esModule: true }
// Expected output is: { Book: f, User: f, login: ƒ, logout: ƒ, __esModule: true }

对此有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用export { default as name } from './resource'将默认值转换为命名导出:

export { default as Book } from './Book'
export { default as User } User from './User'
export * from './userActions'