【问题标题】:How to deconstruct an ES6 module joint export如何解构 ES6 模块联合导出
【发布时间】:2016-11-13 02:11:25
【问题描述】:

我在导出场景中遇到了一些小问题,我不知道为什么。我可能需要一个 Babel 插件来解决它,但不确定是哪个。

// a.js
export function fromA() {}

// b.js
export function fromB() {}

// index.js
import * as a from './a'
import * as b from './b'

export default { ...a, ...b}

// test.js
import all from './index'  
const { fromA } = all // Works

import { fromA } from './index'  // Does not work. Why?

我正在通过 Babel。这是我的 rc:

{
  "plugins":  [
    "transform-object-rest-spread", 
    "transform-class-properties", 
    "transform-export-extensions", 
    "transform-decorators-legacy"
   ], 
  "presets":  ["latest", "react"]
}

似乎我应该能够像往常一样在 import 语句中对 test.js 进行破坏,但不能。如果在 index.js 中,我导出单个函数,那么它就可以了。如:

import { fromA } from './a'
import { fromB } from './b'
export default { fromA, fromB }

但是我想避免这种情况。

【问题讨论】:

  • 虽然导入语法看起来像解构,但事实并非如此。您正在从 index.js 导出一个对象,因此您只能将其作为整个对象导入。
  • 唯一的例外是当您导入非 es6 模块时。由于 commonjs 模块每个模块只能导出一个变量,因此 babel 会退回到解构导入它们。
  • ^ 这个。此外,import { fromA } from './index' 将不起作用,因为没有 fromA 导出,只有默认值。而fromA 导出不能用`export { ...a, ...b} 实现,因为导入和导出是模仿JS 对象语法并且应该是静态的。

标签: javascript ecmascript-6 es6-modules


【解决方案1】:

虽然导入语法看起来像解构,但其实不是。

当您导出命名变量时,您只能将其作为命名变量导入。而当你导出一个默认变量时,你只能将它作为默认变量导入。

例如:

// a.js
export const foo = 1
export const bar = 2
export default { bar: 42, baz: 33 }
import { foo } from './a'
// foo = 1
import { bar } from './a'
// bar = 2
import a from './a'
// a = { bar: 42, baz: 33 }

唯一的例外是当您导入非 es6 模块时。由于 commonjs 模块每个模块只能导出一个变量,因此 babel 会退回到解构导入它们。

因此,由于您要从 index.js 导出单个对象,因此您只能将其作为整个对象导入。


您正在寻找的可能是export * from 声明:

export * from './a'
export * from './b'

它将重新导出两个模块中的所有命名导出。

【讨论】:

    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2016-11-16
    • 2015-01-03
    相关资源
    最近更新 更多