我正在尝试将Angular 1.x与新的TS2和@types注册表一起使用,但遇到了问题。看起来@types不会使用打字注册表所指的内容,而是#34; global"分型。我遇到了以下错误:
error TS2686: 'angular' refers to a UMD global, but the current file is a module. Consider adding an import instead.
角度代码如下:
import "angular";
import "angular-route";
const app = angular.module("charter-app", ["ui.bootstrap", "ui.router", "templates", "charter-app.controllers"]);
tsconfig.json:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"mapRoot": "./",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"target": "es5",
"inlineSources": true,
"removeComments": false,
"noImplicitAny": false,
"typeRoots": [ "node_modules/@types/" ],
"types": [ "angular", "angular-ui-bootstrap", "angular-ui-router" ],
"outFile": "app.js"
}
}
尝试使用以下
"devDependencies": {
"@types/angular": "^1.5.20",
"@types/angular-ui-bootstrap": "^0.13.35",
"@types/angular-ui-router": "^1.1.34",
我使用gulp-typescript进行编译。我错过了什么?我可以不为此目的使用@types库吗?
答案 0 :(得分:38)
我可以在这里想到两种方法。
1)将角度标记为global 。 (更容易迁移选项)
创建一个d.ts
文件说overrides.d.ts
并执行:
declare global {
const angular: ng.IAngularStatic;
}
export {};
或
import * as _angular_ from 'angular';
declare global {
const angular: typeof _angular_;
}
就是这样,不需要import
或单独管理脚本加载。
2)在每个受影响的文件中导入它。 (对于大型现有项目,可能是更繁琐的迁移选项)
如果你可以继续更新所有受影响的文件(通常有点难以在一个已经有很多错误的大项目中采用这种方法),你引用angular
,导入它:
import * as angular from "angular";
如果您采用这种方法,typescript将使用angular
作为文件的依赖项进行转换,并且您的模块加载器(例如:SystemJS
)需要处理导入。这可以通过让systemJS通过地图/路径管理导入来完成,或者如果脚本是由script
标签加载的,那么您可以使用 {{3}为angular
创建假模块。 } apis。
答案 1 :(得分:3)
答案 2 :(得分:1)
我正在为Webstorm IDE构建文件监视器并遇到了这个问题。要解决此问题,我必须删除@types/angular
,在我的编译中添加typings angular
也包含typings angular
,方法是添加以下选项:
--types {your file dir}/typings/index.d.ts
。同样,您可以将其添加到tsconfig.json
我知道这不是你所希望的解决方案,但它让我超越了那个驼峰。