Typeular 2.x,@ type和SystemJS的Angular 1.x - 使用全局类型

时间:2016-11-17 20:21:38

标签: angularjs typescript typescript-typings typescript2.0

我正在尝试将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库吗?

3 个答案:

答案 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)

将此导入添加到您的代码

import * as angular from "angularjs";

有关详细信息,请参阅Typescript Angular Import

答案 2 :(得分:1)

我正在为Webstorm IDE构建文件监视器并遇到了这个问题。要解决此问题,我必须删除@types/angular,在我的编译中添加typings angular也包含typings angular,方法是添加以下选项: --types {your file dir}/typings/index.d.ts。同样,您可以将其添加到tsconfig.json

我知道这不是你所希望的解决方案,但它让我超越了那个驼峰。