【问题标题】:Angular 7 & Stripe error TS2304: Cannot find name 'Stripe'Angular 7 & Stripe 错误 TS2304:找不到名称“Stripe”
【发布时间】:2019-07-12 04:44:57
【问题描述】:

我已经安装了@types/stripe-v3 并将Stripe 的javascript 文件包含在index.html 的脚本标记中。假设 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'.

【问题讨论】:

  • 为Stripe定义import语句怎么样?
  • 如果你尝试像import { Stripe } from 'stripe-v3'; 这样的导入语句,你会得到错误'stripe-v3 is not a module',因为 index.d.ts 文件确实没有声明模块,这意味着在编译器包含时声明此全局变量 Stripe
  • yarn add @types/stripe-v3 --save

标签: typescript angular-cli stripe-payments definitelytyped angular-cli-v7


【解决方案1】:

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

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

此解决方案由bjornharvoldthis thread 中发布。

【讨论】:

  • 就我而言,我使用的是@types/stripe-checkout。我遇到了同样的问题,将stripe-checkout 添加到types 数组不起作用。相反,我将@types/stripe-checkout 添加到解决问题的数组中。希望这可以帮助其他人。
  • npm install --save @types/stripe-v3 (我认为我会建议任何新手明确)
  • @jesper 正是我想要的。我挖了好几个小时。
  • 我有我的 tsconfig.base.jsontsconfig.app.json 文件设置,如此处所述。这删除了编辑器中的红色波浪线,但实际的打字稿编译仍然抱怨 OP 提到的错误消息。 :(
  • 尝试删除下面答案中提到的类型数组
【解决方案2】:

Angular 根据来自 typescript 配置文件的 compilerOptions.typescompilerOptions.typeRoots 的值导入类型。 TS compilerOptions docs reference

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

  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: [].

默认情况下,tsconfig.app.json 中的 compilerOptions.types 将有一个空数组作为其值。这就是为什么 Angular 没有自动从node_modules/@types/* 获取已安装的类型的原因。

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

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

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

如果您从 compilerOptions 中删除 types,则 Angular 将自动导入所有未来的类型。

还要确保在tsconfig.js 中检查typestypeRootstypeRoots 将有相对路径作为数组,同样的逻辑也适用于此。

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2019-12-03
    • 1970-01-01
    • 2016-12-18
    • 2019-05-06
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多