【问题标题】:Export entire module through default export通过默认导出导出整个模块
【发布时间】:2020-07-02 19:04:45
【问题描述】:

我有一个包含以下内容的模块:

  • 一个类(称为 Foo)
  • 一个界面(称为 Bar)
  • 类的一个实例(无名称)

我想通过默认导出导出所有这些,以便我可以通过以下方式访问它们:

import foo from './foo'

foo // this is the instance of the class
foo.Foo // the class
foo.Bar // the interface

我可以通过导出命名空间很容易地做到这一点,但是 eslint 禁止命名空间以支持常规的 ES6 导出语法(据我所知,这是有充分理由的)。

【问题讨论】:

  • 你的 tsconfig 是什么样的?它可以取决于您是否有--isolatedModules 标志
  • 我不知道有这样的标志。研究一下,谢谢。 (我没有为标志设置值,所以我使用默认值)。

标签: typescript


【解决方案1】:

我个人更喜欢命名导出而不是默认导出,您可以通过使用命名导出来实现类似的效果:

在你[module].ts

class Foo {}
interface Bar {}
const instance = new Foo()

export { Foo, Bar, instance }

在您要导入的文件中:

import * as foo from '[path to your module]'

你可以这样使用它:

class Dummy extends foo.Foo {}
class Car implements foo.Bar {}
console.log(foo.instance)

您可以使用默认导出来导出对象,但不包括接口,因为接口是类型,不能用作在该对象内部分配的值。 所以你可以这样做:

export default {
  instance,
  Foo
}

你可以这样使用:

import foo from '[path to module]'
class Dummy extends foo.Foo {}
console.log(foo.instance)
// no interface available so this won't work
class Car implements foo.Bar {}

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 2022-07-10
    • 2017-09-23
    • 1970-01-01
    • 2017-05-11
    • 2019-11-22
    • 2021-05-28
    • 2017-04-29
    • 2022-11-02
    相关资源
    最近更新 更多