angular - 如何使用 web-ext-types 避免错误 TS2304
我正在尝试使用 Angular 6 构建一个网页扩展,因此我找到了 web-ext-types 来声明网页扩展 API 的类型。
所以只是尝试创建一个新的 Angular 项目,更新 tsconfig.json 以包含 node_modules/web-ext-types 似乎可以完成工作,因为我可以在 Visual Studio Code 中看到 browser 被识别为类型。到目前为止,一切顺利。
现在我想通过运行 ng build --aot 来构建我的项目,但我遇到了以下错误:error TS2304: Cannot find name 'browser'。
我哪里做错了?
tsconfig.json:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"typeRoots": [
"node_modules/@types",
"node_modules/web-ext-types"
],
"lib": [
"es2017",
"dom"
],
"paths": {
"myLibrary": [
"projects/my-library"
],
"myLibrary/*": [
"projects/my-library/*"
]
}
}
}
tsconfig.app.json:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/app",
"module": "es2015",
"types": []
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}
也来自 angular.json :
"tsConfig": "projects/extension/tsconfig.app.json",
创建了一个 GitHub 仓库来展示完整代码以重现我的问题:https://github.com/benk79/angular-web-ext-base
答案#1
这里的问题是 tsconfig.app.json 中的这个设置:
"compilerOptions": {
"types": []
},
这告诉 Angular CLI 在没有类型包的情况下运行 TypeScript 编译器,覆盖 tsconfig.json 中的 typeRoots 设置。这也解释了为什么你的 IDE 知道 browser 命名空间,但 Angular CLI 不知道,因为 IDE 只是使用 tsconfig.json 配置,而不是特定于 Angular CLI 的 tsconfig.app.json。只需删除 tsconfig.app.json 中的 types 设置,问题就应该解决了。
