【问题标题】:Cannot find namespace 'MyApp' after Angular and Typescript updateAngular 和 Typescript 更新后找不到命名空间“MyApp”
【发布时间】:2020-03-18 11:03:22
【问题描述】:

我有一个类型定义文件,其中我的应用程序的所有 dto 对象都暴露在全局范围内。

DtosGenerator.d.ts

declare module MyApp.Rest.Dto {
   interface IAJsonDto {
   }
 }
 declare module MyApp.Rest.Dto.Post {
   interface ITest1PostDto extends MyApp.Rest.Dto.IAJsonDto {
    code: string;
 }
interface ITest2PostDto extends MyApp.Rest.Dto.IAJsonDto {
    id: number;
 }
interface ITest3PostDto extends MyApp.Rest.Dto.IAJsonDto {
    id: number;
}
  ....
}

并通过以下方式消费。

file1.service.ts

import ITest3PostDto = MyApp.Rest.Dto.Post.ITest3PostDto;

我的应用程序是基于 Angular 框架构建的,我刚刚分别完成了从 Angular(8)、Typescript(3.5.3) 到 Angular9、Typescript(3.6.4) 的迁移。在迁移之前,对 Dto 对象的消耗没有产生任何错误,一切看起来都很正常。迁移后,当应用程序在手表模式下运行时,

ng build --extractCss=true --watch 命令,控制台输出'Cannot find namespace 'MyApp'。当我添加

/// <reference path="../../../../DtosGenerator.d.ts" /> 

在文件顶部不再产生错误。有没有办法在不添加引用路径的情况下保持我的代码在迁移之前的样子。

谁能告诉我怎么回事?

【问题讨论】:

    标签: angular typescript angular-cli


    【解决方案1】:

    对于任何面临同样问题的人,我找到了解决方案。经过数小时的研究,我发现 Angular 自动更新 (https://update.angular.io/) 更改了 tsconfig.app.json 文件配置。

    迁移前的tsconfig.app.json

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
      "outDir": "../out-tsc/app",
      "types": [ "node" ],
      "typeRoots": [
         "node_modules/@types"
      ]
    },
    "exclude": [
      "test.ts",
      "**/*.spec.ts"
    ]
    }
    

    迁移后的tsconfig.app.json:

    {
     "extends": "../tsconfig.json",
     "compilerOptions": {
       "outDir": "../out-tsc/app",
       "types": [ "node" ],
       "typeRoots": [
         "node_modules/@types"         
       ]
    },
    "files": [
       "main.ts",
       "polyfills.ts"
     ],
    "include": [
      "src/**/*.d.ts"
    ]
    }
    

    问题在于,在迁移之前,所有文件都包含在编译过程中,而在迁移之后,仅包含“files”数组中指定的 2 个文件和 src 目录中的所有类型定义文件。 'DtosGenerator.d.ts' 文件位于 src 文件夹的根目录中,因此需要进行一些修改才能生成最终正确的 tsconfig.app.json 文件。

    tsconfig.app.json 最终版

    {
       "extends": "../tsconfig.json",
       "compilerOptions": {
       "outDir": "../out-tsc/app",    
       "typeRoots": [
          "node_modules/@types"      
       ]
    },
      "files": [
        "main.ts",
        "polyfills.ts"
      ],
      "include": [
         "*.d.ts"
      ]
    }
    

    【讨论】:

    • 你帮我解决了我的问题,我有一个 Angular 6 应用程序,我正在升级到 11,目前正在迁移到 9,我有一堆命名空间需要添加到包含的属性中tsconfig.app.json{ "include": ["app/path/to/files/*.ts"] }
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2021-11-18
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多