我是 Javascript、Node 和 Typescript 的新手,正在努力使用它们。
长话短说
- 我们如何使用 Typescript 正确构建 Node 包?
- 我们如何在一个漂亮的文件中正确构建与 Node 包 API 匹配的声明文件?
这是我的故事:
我想使用 Typescript 将 javascript 库编码为 Node.js 格式。最后,我想生成适当的声明文件以供将来的 Typescript 开发使用。我使用 gulp-typescript
来编译它们。
经过数小时的研究和错误...
这是我所做的:
foo.ts
export class Foo {
private id: number;
constructor() {
this.id = 0;
}
}
impl.ts
import foo = require('foo');
export function make(): boolean {
var f = new foo.Foo();
return true;
}
main.ts
declare module 'test' {
export import impl = require('impl');
}
module.exports = {
impl: require('impl')
};
gulpfile.js
var gulp = require('gulp')
, ts = require('gulp-typescript');
var TS_FILES = 'src/**/*.ts';
gulp.task('default', ['build_node']);
// Compile the node package from Typescript source code
gulp.task('build_node', function() {
var project = ts.createProject({
declarationFiles: true,
emitDecoratorMetadata: true,
module: 'commonjs',
noEmitError: true,
noImplicitAny: true,
removeComments: true,
target: 'ES5'
});
var tsResult = gulp.src(TS_FILES)
.pipe(ts(project));
tsResult.js
.pipe(gulp.dest('build'));
tsResult.dts
.pipe(gulp.dest('definition'));
});
这是我得到的:
- 3个声明文件:
foo.d.ts
export declare class Foo {
private id;
constructor();
}
impl.d.ts
export declare function make(): boolean;
main.d.ts
declare module 'test' {
export import impl = require('impl');
}
- 3 个javascript 文件:
foo.js
和 impl.js
看起来很正常。还有……
main.js
module.exports = {
impl: require('impl')
};
我什至不知道它是否有效,但可以肯定的是,它对我来说看起来不对......我的意思是我真的认为我搞砸了而且这不是构建 Node 包和声明的正确方法文件。
原因?
当我查看 DefinitelyTyped 声明文件时,它们中的大多数都在一个文件中,每个 export
声明都很好地包含如下:
declare module 'test' {
export function make(): boolean;
...
}
然后有一个 Node 包公开其 API 如下:
module.exports = {
version: '1.0',
impl: require('impl');
}
我阅读了数百篇文章,但似乎没有任何文章能生成我想要的内容。
你能给我解释一下吗:
- 我们如何使用 Typescript 正确构建 Node 包?
- 我们如何在一个漂亮的文件中正确构建与 Node 包 API 匹配的声明文件?
编辑:我没有使用export =
,因为我希望能够在一个文件中声明和导出多个内容。例如:在同一个文件中有一个类和构造函数辅助函数。
最佳答案
有很多方法可以做到这一点,因为还没有官方支持。您可以在此处跟踪官方支持:https://github.com/Microsoft/TypeScript/issues/2338
但是我使用 https://github.com/TypeStrong/atom-typescript#packagejson-support
NPM 上的示例项目:https://github.com/basarat/ts-npm-module
示例项目使用来自 NPM 的项目:https://github.com/basarat/ts-npm-module-consume
关于node.js - 使用 Typescript 1.5 构建 Node 包并生成声明文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31163503/