在typescript项目中,我需要使用bytewise npm模块。这个包在DefinitelyTyped npm名称空间中没有类型定义,所以我不能使用typescript文档中描述的方法:
npm install --save-dev @types/bytewise因为这个模块没有类型声明,所以不可能使用它,因为tsc抱怨:error TS2307: Cannot find module 'bytewise'。
为了解决这个问题,我为bytewise编写了一个声明文件,并将其添加到node_modules/@types/bytewise/index.d.ts中,它工作得很好。
然而,这是一个繁琐的常见模式:我使用一个没有@types声明的小型npm库,在node_modules/@types下创建一个目录,添加一个包含该库声明的index.d.ts,然后使用git force/add该文件(因为node_modules在默认情况下被忽略)。
显然,我不打算永远在我的私有node_modules目录下维护这些声明,最终我想将它们贡献给DefinitelyTyped,这样以后可以更容易地安装它们,但我宁愿在项目的根目录下有一个单独的vendor.d.ts文件,所有声明在npm上都不可用,而不是为我使用的每个库创建单独的目录/文件。如下所示(这是我的项目ATM中的内容):
import bl = require("bl");
import {Stream} from "stream";
declare module "bytewise" {
export function encode(val: any): bl;
export function decode(val: bl): any;
export const buffer: boolean;
export const type: string;
}
declare module "JSONStream" {
export function parse(patternOrPath?: string): Stream;
export function stringify(open?: string, sep?: string, close?: string);
}问题是:如何使这些声明对项目中的所有文件可用?我已经尝试修改tsconfig.json,使其包含在入口点之前:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"outDir": "out",
"sourceMap": true
},
"files": [
"vendor.d.ts",
"index.ts"
]
}但仍然在我有import * as bytewise from "bytewise";的文件中获得error TS2307: Cannot find module 'bytewise'.。我还尝试添加指向vendor.d.ts的/// <reference path="..." />注释,但得到了相同的错误。我真的需要为每个npm模块都有一个单独的声明文件吗?还是我遗漏了什么?
发布于 2017-08-16 00:08:26
只需在项目中包含vendor.d.ts,无需特殊配置,但有一个关键更改:将顶部的两个导入移到该行之后
declare module "bytewise" {声明之外的任何导出或导入都将导致此操作失败,并显示如下隐含的消息:
Error:(3, 16) TS2665:Invalid module name in augmentation. Module 'bytewise' resolves to an untyped module at 'my-project/node_modules/bytewise/bytewise.js'.
https://stackoverflow.com/questions/40720476
复制相似问题