Angular 7&Stripe错误TS2304:找不到名称'Stripe'

问题描述 投票:1回答:1

我已经安装了@types/stripe-v3,并在index.html的脚本标签中包含了Stripe的javascript文件。据推测,Angular编译器应该从@types节点模块自动包含所有文件。在互联网上阅读并查看@types/stripe-v3/index.d.ts,如果编译器包含该文件,则应该全局声明var Stripe。来自index.d.ts

declare var Stripe: stripe.StripeStatic;

在我的服务文件中,我有以下代码:

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class BetalingService {
  stripe = Stripe(environment.stripeKey);

  constructor() { }

}

导致以下错误:

error TS2304: Cannot find name 'Stripe'.
typescript angular-cli stripe-payments definitelytyped angular-cli-v7
1个回答
5
投票

通过在您的Angular项目的@types/stripe-v3目录中的compilerOptions.types文件的tsconfig.app.json数组中包含对src包的引用来解决该问题。

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "stripe-v3"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

此解决方案由bjornharvoldthis thread发布。


1
投票

Angular导入类型基于typescript配置文件中的compilerOptions.typescompilerOptions.typeRoots的值。 TS compilerOptions docs reference

默认情况下,使用angular cli创建的Angular项目将具有两个打字稿配置文件。

  1. tsconfig.json在项目的根源
  2. tsconfig.app.json/src目录中

如果typestypeRoots都未定义,则将从node_modules/@types/*导入所有类型。

但是,如果它们中的任何一个具有任何值,则仅导入指定类型或指定位置的类型。例如:types: ['stripe-v3'] or typeRoots: ['/someDir']。因此,node_modules/@types/*中的所有其他已安装类型都不会被导入。

如果设置了空数组,则不会从node_modules/@types自动导入任何类型。 types: [] or typeRoots: []

默认情况下,compilerOptions.types中的tsconfig.app.json将有一个空数组作为其值。这就是为什么角度不能自动从node_modules/@types/*获得已安装的打字的原因。

解决这个问题:npm install @types/stripe-v3的打字和tsconfig.app.json

  1. 要么将stripe-v3添加到types
...
"compilerOptions": {
   ...
  "types": ['stripe-v3']
}
  1. 或者从compilerOptions中删除类型

如果添加,则必须将所有未来的打字添加到此数组中。

相反,如果你从types中删除compilerOptions angular会自动导入所有未来的打字。

另外一定要检查types中的typeRootstsconfig.jstypeRoots将相对路径作为数组,同样的逻辑也适用于此。

© www.soinside.com 2019 - 2024. All rights reserved.