包含第三方库的类型会导致未通过 angular CLI 找到模块?

Rea*_*ues 14 typescript angular mapkit-js

我试图在我的 Angular 9 应用程序中包含 Apple MapKit JS 的类型,因为库没有提供高质量的类型,@types作用域包中也没有任何好的第三方类型。然而,Angular CLI 对我如何包含我的类型并不满意。我在编译时收到的确切错误是:

Module not found: Error: Can't resolve 'mapkit' in `components/map.component.ts`.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

打字

~src/types/mapkit/index.d.ts

这是类型声明的地方,以及它们是如何声明的。

Module not found: Error: Can't resolve 'mapkit' in `components/map.component.ts`.
Run Code Online (Sandbox Code Playgroud)

打字稿配置

配置文件

declare module 'mapkit' {
  // interfaces, classes, etc here
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.app.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2019",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

Run Code Online (Sandbox Code Playgroud)

代码中的用法

这是如何mapkit使用的。

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Dra*_*g13 4

Long story short: You need to rename your folder with types and add them to the type roots.

Step #1

In your folder with types (./types) create new folder "apple-mapkit-js"

Step #2

Add your custom index.d.ts there

Step #3 Point TSC to your custom types. Update tsconfig.app.json with new typeRoots:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "typeRoots" : ["./src/types/", "node_modules/@types"]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
}
Run Code Online (Sandbox Code Playgroud)

Step #4 Update your import to the

import * as mapkit from 'apple-mapkit-js'
Run Code Online (Sandbox Code Playgroud)

Now it works.

But what was the issue?

Actually, according to the TypeScript documentation, if you specify typeroots, all other resources become "invisible" for the typescript, so tsc just didn't see your declarations

P.S. Checked on the Angular 9 app.