TypeScript:从node_modules导入外部模块

7
有一个npm模块one-two-three。例如,它包含了TS文件index.ts(主文件)和functions.tsfunctions.ts:
export interface IPoint {
    x: number;
    y: number;
}

export function sum(a: IPoint, b: IPoint): IPoint {
    return {
        x: a.x + b.x,
        y: a.y + b.y
    };
}

index.ts:

import functions = require("./functions");

export var sum: typeof functions.sum = functions.sum;

编译:
tsc --module commonjs --declaration index.ts

文件已创建:index.jsindex.d.tsfunctions.jsfunctions.d.ts。 好的。

还有另一个库依赖于one-two-three

npm install --save one-two-three

我想要引入依赖并使用来自 functions.ts 的接口。

import mo = require("one-two-three");

错误 无法找到外部模块 'one-two-three'

/// <reference path="node_modules/one-two-three/index.d.ts" />
import mo = require("one-two-three");

没有反应。
import mo = require("./node_modules/one-two-three");

失败。
declare var require;

var mo = require("one-two-three");    

它可以成功编译。 但是没有类型检查。 可以编写:mo.unknownFunction(),并且它将被编译。 无法使用接口。

如何正确实现上述描述?

更新

我已经按照以下所述实现了所需的行为。 编辑 d.ts 文件。

functions.d.ts:

declare module "one-two-three.functions" {
    export interface IPoint {
        x: number;
        y: number;
    }
    export function sum(a: IPoint, b: IPoint): IPoint;
}

index.d.ts:

/// <reference path="./functions.d.ts" />

declare module "one-two-three" {
    import functions = require("one-two-three.functions");
    export var sum: typeof functions.sum;
}

使用它:

/// <reference path="node_modules/one-two-three/index.d.ts" />
/// <reference path="node_modules/one-two-three/functions.d.ts" />

import oneTwoThree = require("one-two-three");
import functions = require("one-two-three.functions");
import IPoint = functions.IPoint;

function delta(a: IPoint, b: IPoint): number {
    var dx: number = a.x - b.x,
        dy: number = a.y - b.y;
    return Math.sqrt(dx * dx + dy * dy);
}

var point1: IPoint = {x: 10, y: 20},
    point2: IPoint = {x: 5, y: 5};

console.log(oneTwoThree.sum(point1, point2));
console.log(delta(point1, point2));

成功了。 但我们必须双重努力。 编写代码并单独描述接口。

是否有一种方法生成正确的d.ts文件? 问题在于d.ts文件应该使用内部语法(module {})来描述模块。 但源文件是CommonJS模块。 它没有module部分。

1个回答

6
/// <reference path="node_modules/one-two-three/index.d.ts" />
import mo = require("one-two-three");

没有反应。

应该可以工作。

TypeScript中的.d.ts文件类似于C语言中的.h文件。当从另一个项目或子项目导入依赖项时使用它是很正常的。

如果文件your-project/node_modules/one-two-three/index.d.ts没有正确编写,建议将其复制到your-project/one-two-three.d.ts,然后修复副本。使用模块名称作为文件名使得/// <reference是可选的。只需写:

import mo = require("one-two-three");

但是不起作用 :(据我所知,d.ts文件必须具有以下视图:module "one-two-three" {...}但它被编译为--module commonjs,并且仅包含没有“module”语句的函数。 - vasa_c
你能修复 .d.ts 文件吗? - Paleo
是的,我可以做到,但我不想这样做。我已经在问题中添加了UPDATE。 - vasa_c
好的,明白了。 我会手动编写d.ts文件。 谢谢你,Tarh! - vasa_c

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接