node.js - 使用 Typescript 1.5 构建 Node 包并生成声明文件

标签 node.js typescript declaration

我是 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;
}

ma​​in.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;

ma​​in.d.ts

declare module 'test' {
    export import impl = require('impl');
}
  • 3 个javascript 文件:

foo.jsimpl.js 看起来很正常。还有……

ma​​in.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/

相关文章:

node.js - 如何在nodejs中重定向页面

Node.js Cluster + Express 始终调用同一个工作线程

angular - 键值对数组转化为数组对象

c++ - 我应该将乘数声明为常量还是直接使用而不声明?

javascript - 使用 jquery .delegate 未调用函数

javascript - 无法导入我的路线模块

javascript - 配置 MailDev 将邮件中继到外部服务器

TypeScript:如何从函数返回字段的类型

typescript - 在 VUE 中,哪种共享模板和逻辑的方法更受欢迎?

c - 结构后面的词是什么?