Typescript 在本地声明第三方模块

Zhe*_*Zhe 7 typescript typescript-typings typescript2.0

我正在构建一个打字稿项目并使用非打字稿库调用“draggabilly”;

所以我试图自己声明。

这是文件结构:

??? @types
?   ??? draggabilly
?       ???index.d.ts
??? node_modules
??? package.json
??? README.md
??? src
?   ??? index.ts
?   ??? application.ts
??? tsconfig.json
Run Code Online (Sandbox Code Playgroud)

源代码/应用程序.ts

import * as Draggabilly from 'draggabilly';

new Draggabilly('#dragItem', {
  // options...
});

......
Run Code Online (Sandbox Code Playgroud)

这表明

找不到模块“draggabilly”的声明文件。'/node_modules/draggabilly/draggabilly.js' 隐含地有一个 'any' 类型。

所以我尝试创建本地声明文件:@types/draggabilly/index.d.ts:

export as namespace draggabilly;

export = Draggabilly;

declare class Draggabilly {
  constructor(selector: string, options: any);
}
Run Code Online (Sandbox Code Playgroud)

然后在 tsconfig.json 中包含类型路径:

{
    "compilerOptions": {
        ......
        "typeRoots": [
            "./node_modules/@types",
            "./@types"
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

但是错误仍然存​​在。所以我想知道这里有什么问题以及在本地构建第三方模块声明文件的正确方法是什么

我在github上为这个问题创建了一个演示库:https : //github.com/ZheFeng/test-ts-types

问题不仅在于我们如何在 .d.ts 文件中定义,还在于打字稿根本找不到声明文件。

Sar*_*ana 4

问题出在这一行export = Draggabilly;——你必须使用 TypeScript 特定的语法import let = require("module")来导入它:

来自TypeScript 文档

使用export = 导入模块时,import let = require("module")必须使用特定于TypeScript 的模块来导入。

所以你的导入应该是:

import Draggabilly = require("draggabilly");


如果你想使用ES6风格的导入,你可以修改index.d.ts如下:

export as namespace draggabilly;

export class Draggabilly {
  constructor(selector: string, options: any);
}
Run Code Online (Sandbox Code Playgroud)

...并像这样导入它:

import * as draggabilly from 'draggabilly';

new draggabilly.Draggabilly('#dragItem', {
  // options...
});
Run Code Online (Sandbox Code Playgroud)