我阅读了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';

我做错了什么?


当前回答

对于在React、tsconfig.json中遇到此错误的人,请设置

"compilerOptions" : {
  ...
  "strict": false,
  ...
}

React的create-React应用程序自动生成的配置将该标志设置为true

其他回答

如果导入不适用于您

import * as html2pdf from 'html2pdf.js';

注释代码,将以下脚本文件保存在index.html中,如官方文档中所示。

<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>

并在正在使用的组件中声明html2pdf变量。

declare var html2pdf: any;

就是这样。我在这个问题上纠结了两天,但最终得到了解决。

创建具有任意名称和.d.ts扩展名的文件。

例如:index.d.ts

将此文件名推送到tsconfig.json文件的include键下:

  "include": [
    "src",
    "index.d.ts"
  ]

如果您已经安装了模块,但仍然收到错误,一个简短而简单的解决方案是通过在该行上方添加以下行来忽略错误消息

// @ts-ignore: Unreachable code error

只需使用require将其导入,如下代码所示:

var _ = require('your_module_name');

基于Retsam的回答,您还可以在Declarations.d.ts文件中使用通配符(*)。例如,如果您试图导入一个文件,例如.css或.webp文件,可以在文件类型声明的开头放置一个*。看起来像这样⤵︎

declare module '*.webp';

现在,您可以导入所需的所有.web文件,而不会出现任何linting错误。