首页 > 解决方案 > 使用 Typescript 和 Webpack 管理依赖项的 AngularJS

问题描述

我的团队的任务是迁移一个 AngularJS 应用程序以使用 Webpack 作为与 TypeScript 相结合的构建系统。这一切都是为了将​​应用程序从 AngularJS 逐步迁移到 Angular 做准备。(我们遵循 Angular 团队提供的迁移指南)

今天我遇到了 TypeScript 的“导入”语句的问题,我似乎找不到原因。我找到了解决方案,但想知道为什么会这样。

在这个测试运行中,我在 2 个不同的文件中有 2 个模块。AuthModuleLoginModule。我认为他们的依赖在AuthModule -> LoginModule -> AuthModule中是循环的

//in auth.module.js (this module is loaded before LoginModule)
import {LoginModule} from './login.module'; //is just an exported string

const authModule = angular.module('auth.module', [LoginModule])';
...


//in login.module.js
import {AuthModule} from './auth.module'; //again just an exported string

const LoginModule = angular.module('login.module', [AuthModule]);
...

这些只是 2 个小片段,这是构建的,在浏览器中查看时一切正常。

但是,当我将文件转换为 TypeScript 时,它似乎并不喜欢这种循环依赖。该应用程序内置 webpack 没有错误,但在浏览器中被炸毁。

为了解决这个问题,我不需要在LoginModule中“导入” AuthModule ,并且在提供对 LoginModule 的依赖项时,我需要提供本地字符串而不是导入的字符串。

//in login.module.ts (don't import AuthModule)
const LoginModule = angular.module('login.module', ['auth.module']); //just provide the name of the module here as a string
...

这构建和工作正常,我对此很好,但想了解原因。TypeScript 导入和“webpack”导入有什么区别。我的.tsconfig模块属性设置为CommonJS。这是为什么?

标签: javascriptangularjstypescriptwebpacktsconfig

解决方案


据我了解,当您导入 LoginModule 时,您正在导入该 LoginModule 的实例,因此 angular.js 会引发错误。相反,您需要在该模块声明中提供一个字符串,这就是它起作用的原因。


推荐阅读