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

我做错了什么?


当前回答

在大多数情况下,您可能会为依赖项安装一个类型包,无论是哪种方式,都可以在tsconfig.json文件中添加allowJs->true

其他回答

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

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

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

解决方案:您所要做的就是编辑TypeScript Config文件tsconfig.json,并添加一个新的键值对作为

"compilerOptions": {
"noImplicitAny": false
}

不幸的是,包编写者是否对声明文件感到困扰,我们无法控制。我倾向于创建一个像index.d.ts这样的文件,其中包含各种包中所有缺失的声明文件:

索引.d.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

并在tsconfig.js中引用它:

"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "index.d.ts" // this
  ]

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

// @ts-ignore: Unreachable code error

这种方式对我有效:

1.在声明文件(例如index.d.ts)中添加自己的声明(可能在项目根目录下)

declare module 'Injector';

2.将index.d.ts添加到tsconfig.json

  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }