我正在尝试使用Angular 1。使用新的TS2和@types注册表,但遇到了问题。看起来@types并没有使用类型注册表所称的"全局"类型。我遇到了以下错误:
error TS2686: 'angular' refers to a UMD global, but the current file is a module. Consider adding an import instead.
angular代码如下:
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库用于此目的吗?
我可以想到两种方法。
1)将angular标记为全局。(更容易的迁移选项)
创建一个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
标签加载的,那么你可以使用 SystemJS.registerDynamic
或SystemJS.set
api为angular
创建一个假模块。
将此导入添加到您的代码
import * as angular from "angularjs";
参见Typescript Angular Import获取更多信息
我正在为Webstorm IDE构建一个文件监视器,并遇到了这个问题。为了解决这个问题,我不得不删除@types/angular
,添加typings angular
,并通过添加选项将typings angular
包括在我的编译中:--types {your file dir}/typings/index.d.ts
。类似地,您可以将其添加到tsconfig.json
我知道这不是你想要的解决方案,但它让我度过了难关。