我阅读了TypeScript模块解析的工作原理。

我有以下存储库:@tsstack/di。编译后,目录结构如下:

├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json

在package.json中,我写了“main”:“dist/index.js”。

在Node.js中,一切正常,但TypeScript:

import {Injector} from '@ts-stack/di';

找不到模块“@ts stack/di”的声明文件/path/to/node_modules/@tsstack/di/dist/index.js”隐式具有“any”类型。

然而,如果我按如下方式导入,那么一切都正常:

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

我做错了什么?


当前回答

一个简单的解决方案:

// example.d.ts
declare module 'foo';

如果要声明对象的接口(推荐用于大型项目),可以使用:

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

如何使用?易于理解的

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this

其他回答

对我有用的是将依赖项安装为开发依赖项。上述禁用隐式类型检查的解决方案有效,但这使我无法利用严格类型代码。因此,您需要做的就是在所有的@types模块安装中附加--save-dev标志。希望这对你也有用

我已经尝试了这里的一切,但对我来说,这是一个完全不同的问题:我必须从*.d.ts中删除任何导入语句:

import { SomeModuleType } from '3rd-party-module';

删除错误后。。。

澄清:当我们在*.d.ts文件中声明一个模块时,Typescript编译器会自动将其作为环境模块(不需要显式导入的模块)。一旦我们指定了导入。。。从…起该文件现在成为一个正常(ES6)模块,因此不会自动拾取。因此,如果您仍然希望它作为环境模块,请使用不同的导入样式,如下所示:

type MyType: import('3rd-party-module').SomeModuleType;

如果需要快速修复,只需将其添加到导入行之前:

// @ts-ignore

只需在项目的根目录中创建一个名为typings.d.ts的文件。在该文件中,只需添加declare module<module_name>。这里,module_name可以是要导入的任何模块的名称。最后,打开tsconfig.json文件,将文件typeings.d.ts包含在名为include array的数组中。

// typings.d.ts 
declare module 'abc-module';

// tsconfig.json 
{
  ...
"include": [
    "src", "typings.d.ts"
  ]
}

// BOOM, Problem solved!!!

此技术为模块提供了名为“any”的类型。有关详细信息:https://medium.com/@steveruiz/using-a-javascript-library-with-out-type-declarations-in-a-typescript-project-3643490015f3

还有两种解决方案

如果模块不是您的,请尝试从@types安装类型:

npm install -D @types/module-name

如果出现上述安装错误,请尝试更改import语句以要求:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');