【问题标题】:Typescript export syntax & code structuring打字稿导出语法和代码结构
【发布时间】:2015-06-02 22:44:11
【问题描述】:

我正在构建一个打字稿库,我想通过以下方式进行:

  1. 一个class (interface) / 开发源中的文件
  2. 由于整个库“属于一起”,所以都可以放在 1 个命名空间下
  3. 在构建时,我希望能够创建单个输出 jsd.ts 文件,仅使用相关的导出/定义。

我尝试做的方式如下:

我使用/// <reference path="..." /> 语法来引用其他文件

Foo.ts

class Foo {
    // stuff
}

Bar.ts

/// <reference path="Foo" />

class Bar extends Foo {
    // just an example for referencing another compilation unit
}

创建一个tsconfig.json 文件,该文件使用out 选项,因此所有内容都连接到一个文件中:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "ES5",
        "out": "src-gen/app.js"
        /* other options ... */
    }
}

最后添加一个文件,它导出所有的东西,我希望能够从其他文件中导入,像这样:

Exports.ts

/// <reference path="Bar" />

export {Bar} // don't want to expose Foo, since its not relevant for users of the lib.

export {Bar} 行给出以下编译错误:

导入别名'Bar'的循环定义。导入栏

我不知道这个错误是什么意思,因为Bar 不会在任何地方导入,只能使用/// &lt;reference&gt; 语法引用。

最后我的全部目标是,有一个文件,js 文件作为输出,如下所示:

/* compiled js source of Foo */

/* compiled js source of Bar */

exports = {
    Bar
}

我的问题是:

  1. 这是一种有效的做事方式吗?
  2. 如果是,export {Bar} 有什么问题?
  3. 如果没有,您将如何实现,我想做什么?

提前感谢您提供任何帮助/建议!

【问题讨论】:

    标签: build typescript


    【解决方案1】:

    我认为你想要做的是使用模块:

    Foo.js

    module MyModule {
      class Foo {
          // stuff
      }
    }
    

    Bar.js

    module MyModule {
      export class Bar extends Foo {
          // stuff
      }
    }
    

    那么您就不需要 Exports.js,因为只有标有 export 的项目会被导出。

    我相信,如果你一次编译所有文件,你也不需要/// &lt;reference 行。

    编辑: 我想你的问题的答案在这里: Creating a single CommonJS module from several TypeScript classes

    【讨论】:

    • 您好,感谢您的回答,但您确定这应该有效吗?当我做同样的事情时,我得到Module 'MyModule' has no exported member 'Foo'。即使我添加/// &lt;reference path="Foo" /&gt;,或者尝试使用完全限定名(... extends MyModule.Foo)引用MyModule.Foo。 VS Code 和命令行中的错误相同。我忘了提,但我使用的是 typescript 1.5 beta
    • 更新!我一直在玩它,如果我也导出Foo,那么它在Bar.ts 中是可见的,这几乎是我想要的,而且现在还可以。但是我如何从命名空间之外的MyModule 引用类?我试过import Bar from 'Bar'import MyModule from 'Bar',还有import MyModule from 'Bar',但我得到了File Bar.ts is not an external module。这里有什么交易?
    • 你想创建什么样的模块? CommonJS?
    • 我想你的问题的答案在这里:stackoverflow.com/questions/26629340/…
    • 我在您的帖子中添加了评论,因此其他人也可能会看到它。谢谢,这完成了工作:)
    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2018-10-17
    • 2019-04-18
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多