TypeScript:从node_modules导入外部模块

vas*_*a_c 6 typescript

one-two-three例如,有一个npm模块.它包含TS文件index.ts(主要)和functions.ts.

functions.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
    };
}
Run Code Online (Sandbox Code Playgroud)

index.ts:

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

export var sum: typeof functions.sum = functions.sum;
Run Code Online (Sandbox Code Playgroud)

编译:

tsc --module commonjs --declaration index.ts
Run Code Online (Sandbox Code Playgroud)

创建文件:index.js,index.d.ts,functions.jsfunctions.d.ts.好.

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

npm install --save one-two-three
Run Code Online (Sandbox Code Playgroud)

我想包括依赖并使用它和接口functions.ts.

import mo = require("one-two-three");
Run Code Online (Sandbox Code Playgroud)

错误Cannot find external module 'one-two-three'.

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

没有反应.

import mo = require("./node_modules/one-two-three");
Run Code Online (Sandbox Code Playgroud)

失败.

declare var require;

var mo = require("one-two-three");    
Run Code Online (Sandbox Code Playgroud)

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

如何使上述正确?

UPDATE

我已经达到了预期的行为.编辑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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

使用它:

/// <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));
Run Code Online (Sandbox Code Playgroud)

成功.但我们必须做双重责任.编写代码并单独描述接口.

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

Pal*_*leo 5

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

没有反应。

它应该工作。

一个文件.d.ts中的打字稿就像一个文件.h中C.这是正常使用时,它依赖从其他项目或子项目进口。

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

import mo = require("one-two-three");
Run Code Online (Sandbox Code Playgroud)