【问题标题】:Angular 1.x with TypeScript 2.x, @types, and SystemJS - Using global typingsAngular 1.x 与 TypeScript 2.x、@types 和 SystemJS - 使用全局类型
【发布时间】:2017-04-01 13:12:08
【问题描述】:

我正在尝试将 Angular 1.x 与新的 TS2 和 @types 注册表一起使用,但遇到了问题。看起来@types 不使用类型注册表称为“全局”类型的内容。我遇到了以下错误:

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 库吗?

【问题讨论】:

    标签: angularjs typescript typescript-typings typescript2.0


    【解决方案1】:

    我可以在这里想到两种方法。

    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 标签加载,那么您可以使用 SystemJS.registerDynamic or SystemJS.set apis 为 angular 创建一个假模块.

    【讨论】:

    • 你是正确的。这个答案的 10 倍,你解决了我的问题
    • 这解决了我尝试导入fabricjs的问题。谢谢
    • @PSL 将方法 1) 的文件放在哪里?
    • @eXavier 您可以将它放在应用根目录的任何位置。
    • 我正在尝试这个,但我得到了Module not found: Error: Can't resolve './angular' in 'C:\...\node_modules\angular'
    【解决方案2】:

    将此导入添加到您的代码中

    import * as angular from "angularjs";
    

    更多信息请参见Typescript Angular Import

    【讨论】:

    【解决方案3】:

    我在为 Webstorm IDE 构建一个文件观察器时遇到了这个问题。为了解决这个问题,我必须删除@types/angular,添加typings angular,并通过添加选项在我的编译中包含typings angular--types {your file dir}/typings/index.d.ts。同样,您可以将其添加到您的tsconfig.json

    我知道这不是您希望的解决方案,但它让我克服了困难。

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 1970-01-01
      • 2011-08-17
      • 2017-04-06
      • 1970-01-01
      • 2017-01-13
      • 2012-06-20
      • 1970-01-01
      • 2018-08-29
      相关资源
      最近更新 更多