【问题标题】:AngularJS + TypeScript: Uncaught TypeError: Cannot read property 'module' of undefinedAngularJS + TypeScript:未捕获的 TypeError:无法读取未定义的属性“模块”
【发布时间】:2017-09-14 05:37:52
【问题描述】:

我正在尝试在 AngularJS 1.x 应用程序中使用 TypeScript。

我的应用程序已经使用 Webpack 作为模块加载器,所以我将它配置为处理 TypeScript 编译(在将所有 *.js 源文件重命名为 *.ts 之后),我设法让它工作。所以它编译没有错误并生成我的 JavaScript 输出文件。

唯一的问题是,当我在浏览器上运行应用程序时,它不起作用,并且出现此控制台错误:

未捕获的类型错误:无法读取未定义的属性“模块”

还有:

未捕获的错误:[$injector:modulerr] 无法实例化模块 myModuleName,原因如下: 错误:[$injector:nomod] 模块“myModuleName”不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

我的猜测是对象 angular 出于某种原因为空,当我尝试访问 angular.module 时它会抱怨。

我不明白为什么会这样,因为当我在代码中使用import angular from 'angular/angular'; 时,它编译成功。

完整的源代码可在here获取。

Webpack 输出:

Hash: 824157db8ed6acf47fc1 Version: webpack 2.2.1 Time: 2242ms Asset Size Chunks Chunk Names othello-bundle.js 1.27 MB 0 [emitted] [big] app othello-bundle.js.map 1.51 MB 0 [emitted] app [0] ./~/angular/angular.js 1.24 MB {0} [built] [5] ./app/services/othello_AI.ts 8.65 kB {0} [built] [6] ./app/services/othello_handler.ts 9.3 kB {0} [built] [7] ./app/index.ts 723 bytes {0} [built] + 4 hidden modules

【问题讨论】:

  • 你的角度版本是多少?我在 package.json 或 bower.json 中看不到 angular
  • 从我的 package.json 中可以看到它是 1.6:github.com/ShinDarth/Othello/blob/typescript/package.json#L9
  • 我的错,您是否在加载时检查了脚本顺序,或者是否同时加载 angular 和 angular.min?
  • @DMCISSOKHO 我刚刚更新了我的问题,包括 Webpack 构建的输出
  • AngularJs 应该首先包含

标签: javascript angularjs typescript webpack es6-module-loader


【解决方案1】:

我终于找到了解决办法。

使用 TypeScript 时,需要使用以下方式导入 AngularJS:

import * as angular from 'angular';

问题是我仍然像使用 es6 一样导入它:

import angular from 'angular';

【讨论】:

  • 谢谢。这让我发疯了。我可以让我的应用程序使用 angular 作为全局在 webpack 中运行,但业力测试失败并出现 You need to include some adapter that implements __karma__.start method! 错误。包含 import 语句会立即导致使用 webpack 编译的任何内容返回询问者提到的未定义错误的属性。更改我的导入语句修复了它,因此我可以同时工作,并且自从引入 TypeScript 以来第一次没有编译错误:D
猜你喜欢
  • 2015-05-08
  • 2023-01-14
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 2022-12-21
  • 2017-11-02
  • 1970-01-01
  • 2019-05-16
相关资源
最近更新 更多