Typescript 导出语法和代码结构
Typescript export syntax & code structuring
我正在构建一个打字稿库,我想按以下方式进行:
- 一个
class
(interface
) / 开发源中的文件
- 由于整个库 "belongs together",所有都可以在 1 个命名空间下
- 构建时,我希望能够创建单个输出
js
和 d.ts
文件,只包含相关的 exports/definitions.
我尝试的方法如下:
我使用 /// <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}
行给出了以下编译错误:
Circular definition of import alias 'Bar'. import Bar
我不知道这个错误是什么意思,因为 Bar
没有导入任何地方,只能使用 /// <reference>
语法引用。
最后我的整个目标是,有一个文件,js
文件作为输出,如下所示:
/* compiled js source of Foo */
/* compiled js source of Bar */
exports = {
Bar
}
我的问题是:
- 这是一种有效的做事方式吗?
- 如果是,
export {Bar}
有什么问题
- 如果没有,你会怎么实现,我想做什么?
在此先感谢任何 help/advice!
我想你想做的是使用模块:
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
我正在构建一个打字稿库,我想按以下方式进行:
- 一个
class
(interface
) / 开发源中的文件 - 由于整个库 "belongs together",所有都可以在 1 个命名空间下
- 构建时,我希望能够创建单个输出
js
和d.ts
文件,只包含相关的 exports/definitions.
我尝试的方法如下:
我使用 /// <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}
行给出了以下编译错误:
Circular definition of import alias 'Bar'. import Bar
我不知道这个错误是什么意思,因为 Bar
没有导入任何地方,只能使用 /// <reference>
语法引用。
最后我的整个目标是,有一个文件,js
文件作为输出,如下所示:
/* compiled js source of Foo */
/* compiled js source of Bar */
exports = {
Bar
}
我的问题是:
- 这是一种有效的做事方式吗?
- 如果是,
export {Bar}
有什么问题 - 如果没有,你会怎么实现,我想做什么?
在此先感谢任何 help/advice!
我想你想做的是使用模块:
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