我已经安装了@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项目的@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"
]
}
此解决方案由bjornharvold在this thread发布。
Angular导入类型基于typescript配置文件中的compilerOptions.types
和compilerOptions.typeRoots
的值。 TS compilerOptions docs reference
默认情况下,使用angular cli创建的Angular项目将具有两个打字稿配置文件。
tsconfig.json
在项目的根源tsconfig.app.json
在/src
目录中如果types
和typeRoots
都未定义,则将从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
stripe-v3
添加到types
。...
"compilerOptions": {
...
"types": ['stripe-v3']
}
如果添加,则必须将所有未来的打字添加到此数组中。
相反,如果你从types
中删除compilerOptions
angular会自动导入所有未来的打字。
另外一定要检查types
中的typeRoots
和tsconfig.js
。 typeRoots
将相对路径作为数组,同样的逻辑也适用于此。