Rob*_*per 6 stripe-payments typescript definitelytyped angular-cli angular-cli-v7
我已经@types/stripe-v3在中的脚本标签中安装了Stripe的javascript文件,并将其包括在内index.html。假定Angular编译器应自动包含@types节点模块中的所有文件。@types/stripe-v3/index.d.ts如果编译器包含该文件,则在Internet上阅读并查看是否有全局声明的var Stripe。从index.d.ts
declare var Stripe: stripe.StripeStatic;
Run Code Online (Sandbox Code Playgroud)
在我的服务文件中,我有以下代码:
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class BetalingService {
stripe = Stripe(environment.stripeKey);
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
error TS2304: Cannot find name 'Stripe'.
Run Code Online (Sandbox Code Playgroud)
通过在Angular项目的目录中的文件数组中包含对该@types/stripe-v3包的引用,可以解决此问题。compilerOptions.typestsconfig.app.jsonsrc
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": [
"stripe-v3"
]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
此解决方案由bjornharvold在此主题中发布。
Angular 根据打字稿配置文件的值compilerOptions.types和compilerOptions.typeRoots来自打字稿配置文件的值导入类型。
TS compilerOptions 文档参考
默认情况下,使用 angular cli 创建的 Angular 项目将有两个打字稿配置文件。
tsconfig.json 在项目的根目录tsconfig.app.json在/src目录中如果types和typeRoots都未定义 angular 将从node_modules/@types/*.
但是,如果其中任何一个具有任何值,则只会导入指定的类型或来自指定位置的类型。例如:types: ['stripe-v3'] or typeRoots: ['/someDir']。因此,node_modules/@types/*不会导入所有其他已安装的类型。
如果设置了空数组,则不会自动从node_modules/@types. types: [] or typeRoots: [].
默认情况下compilerOptions.typesintsconfig.app.json将有一个空数组作为其值。这就是 angular 不会node_modules/@types/*自动获取已安装类型的原因。
解决这个问题:npm install @types/stripe-v3打字和输入tsconfig.app.json
stripe-v3到types....
"compilerOptions": {
...
"types": ['stripe-v3']
}
Run Code Online (Sandbox Code Playgroud)
如果添加,则必须将所有未来的类型添加到此数组中。
相反,如果您types从compilerOptionsangular 中删除,则会自动导入所有未来的类型。
还要确保检查types并typeRoots在tsconfig.js。
typeRoots将有相对路径作为数组,同样的逻辑也适用于此。
| 归档时间: |
|
| 查看次数: |
1468 次 |
| 最近记录: |