[英]Angular 7 & Stripe error TS2304: Cannot find name 'Stripe'
我安装了@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'.
通过在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"
]
}
此解决方案由bjornharvold在此主题中发布 。
角度导入类型基于typescript配置文件中的compilerOptions.types
和compilerOptions.typeRoots
值。 TS compilerOptions文档参考
默认情况下,使用angular cli创建的Angular项目将具有两个打字稿配置文件。
tsconfig.json
在项目的根目录中 /src
目录中的tsconfig.app.json
如果types
和typeRoots
都是未定义的,则angular将导入node_modules/@types/*
所有node_modules/@types/*
。
但是,如果它们中的任何一个具有任何值,则仅导入指定类型或指定位置的类型。 例如: types: ['stripe-v3'] or typeRoots: ['/someDir']
。 因此,不会导入node_modules/@types/*
所有其他已安装类型。
如果设置了空数组,则不会从node_modules/@types
自动导入任何node_modules/@types
。 types: [] or typeRoots: []
。
默认情况下, compilerOptions.types
在tsconfig.app.json
将有一个空数组作为它的值。 这就是为什么angular不会自动从node_modules/@types/*
获取已安装的node_modules/@types/*
的原因。
解决这个问题: npm install @types/stripe-v3
tsconfig.app.json
和tsconfig.app.json
stripe-v3
添加到types
。 ...
"compilerOptions": {
...
"types": ['stripe-v3']
}
如果添加,则必须将所有未来的打字添加到此数组中。
相反,如果从compilerOptions
删除types
,angular将自动导入所有未来的types
。
另外,请确保在tsconfig.js
检查types
和typeRoots
。 typeRoots
将具有相对路径作为数组,同样的逻辑也适用于此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.