Typescript导出语法&代码结构

时间:2015-05-29 17:27:56

标签: build typescript

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

  1. 开发源中的一个classinterface)/文件
  2. 由于整个图书馆“属于一起”,所有人都可以使用1个名称空间
  3. 构建时,我希望能够创建单个输出jsd.ts文件,只能使用相关的导出/定义。
  4. 我尝试的方法如下:

    我使用/// <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没有在任何地方导入,只使用/// <reference>语法引用。

    我的最终目标是,将一个文件js文件作为输出,如下所示:

    /* compiled js source of Foo */
    
    /* compiled js source of Bar */
    
    exports = {
        Bar
    }
    

    我的问题是:

    1. 这是一种有效的做事方式吗?
    2. 如果是,export {Bar}
    3. 会出现什么问题
    4. 如果不是,你将如何实现,我想做什么?
    5. 提前致谢,任何帮助/建议!

1 个答案:

答案 0 :(得分:2)

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

<强> Foo.js

module MyModule {
  class Foo {
      // stuff
  }
}

<强> Bar.js

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

然后你不需要Exports.js,因为只有标有导出的项目才会被导出。

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

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