15

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

Module not found: Error: Can't resolve 'mapkit' in `components/map.component.ts`.

我究竟做错了什么?

打字

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

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

declare module 'mapkit' {
  // interfaces, classes, etc here
}

打字稿配置

tsconfig.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
  }
}

tsconfig.app.json

{
  "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"
  ]
}

代码中的用法

这是如何mapkit使用的。

import * as mapkit from 'mapkit';
4

2 回答 2

4

长话短说:您需要使用类型重命名文件夹并将它们添加到类型根中。

第1步

在您的类型文件夹中(./types)创建新文件夹“apple-mapkit-js”

第2步

在那里添加您的自定义 index.d.ts

步骤#3 将 TSC 指向您的自定义类型。使用新的 typeRoots 更新 tsconfig.app.json:

{
  "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"
  ],
}

步骤 #4 将您的导入更新为

import * as mapkit from 'apple-mapkit-js'

现在它起作用了。

但问题是什么?

实际上,根据TypeScript 文档,如果您指定 typeroots,则所有其他资源对于 typescript 来说都是“不可见的”,所以 tsc 只是没有看到您的声明

PS 在 Angular 9 应用程序上进行了检查。

于 2020-06-24T10:45:48.170 回答
0

尝试声明一个命名空间

declare namespace mapkit {

并从您的组件中删除您的导入

import * as mapkit from 'mapkit'; //Not needed

由于tsconfig.app.json已包含项目中的定义文件,因此您的命名空间声明无需进一步更改即可工作

"include": [
  "src/**/*.d.ts"
],
于 2020-07-01T07:02:58.750 回答