Typescript在本地声明第三方模块

问题描述 投票:3回答:2

我正在构建一个打字稿项目,并使用非打字的lib调用'draggabilly';

所以我试图自己宣布。

这是文件结构:

├── @types
│   └── draggabilly
│       └──index.d.ts
├── node_modules
├── package.json
├── README.md
├── src
│   ├── index.ts
│   └── application.ts
└── tsconfig.json

SRC / application.ts

import * as Draggabilly from 'draggabilly';

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

......

它表明了这一点

无法找到模块'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);
}

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

{
    "compilerOptions": {
        ......
        "typeRoots": [
            "./node_modules/@types",
            "./@types"
        ]
    }
}

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

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

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

typescript typescript-typings typescript2.0
2个回答
2
投票

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

来自TypeScript documentation

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

所以你的导入应该是:

import Draggabilly = require("draggabilly");


If you want to use ES6-style import, you can modify your index.d.ts like below:
export as namespace draggabilly;

export class Draggabilly {
  constructor(selector: string, options: any);
}

...并像这样导入:

import * as draggabilly from 'draggabilly';

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

0
投票

为非基于TypeScript的第三方模块提供声明文件时,声明模块必须位于全局范围内,并且不能在declare模块外部导入或导出。

// @types/draggabilly/index.d.ts
declare module "draggabilly" {
    class Draggabilly {
        constructor(selector: string, options: any);
    }

    export = Draggabilly;
}

// src/application.ts
import Draggabilly = require("draggabilly");

new Draggabilly("#dragItem", {
    // options...
});
© www.soinside.com 2019 - 2024. All rights reserved.