Angular 8 - 延迟加载模块:错误 TS1323:仅当“--module”标志为 'commonjs' 或 'esNext' 时才支持动态导入

Angular 8 - Lazy loading modules : Error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'

当我将 Angular 从 7 更新到 Angular 8 时,延迟加载模块出现错误

我已经尝试了 angular 升级指南

中的选项

进行了以下更改:

之前

    loadChildren: '../feature/path/sample- 
                         tage.module#SameTagModule'

之后

   loadChildren: () => import('../feature/path/sample- 
                      tags.module').then(m => m.CreateLinksModule)

error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.

您正在使用动态导入,因此您必须像这样更改 tsconfig.json 以将您的代码定位到 esnext 模块

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext", // add this line
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

还要确保检查 tsconfig.app.json 没有像这样的模块和目标配置

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

只是添加到@Tony 的答案,您可能还需要在 tsconfig.app.json 中做同样的事情(更改为 "module": "esnext" )。在我的例子中,tsconfig.json 已经使用 esnext 作为模块,但 tsconfig.app.json 仍在使用 es2015,这导致了这个错误。

只是想将我的经验添加到@Tony 的回答中。 更改 tsconfig.json 后仍然显示错误(红色下划线)。 直到重新打开编辑器(我用的是VSCode)才看到红色下划线消失了。

我认为正确的做法是调整 tsconfig.app.json 而不是 tsconfig.json

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "esnext",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

tsconfig.app.json 是特定于 app 的 Typescript 配置文件,位于 Angular workspace[=35] 的根目录下=]. tsconfig.app.json 存在,因此如果您正在构建一个包含 多个 应用程序的 Angular 工作区,您可以分别为每个应用程序调整 Typescript 配置,而无需编写在应用程序之间重叠的冗余配置属性(因此 extends 属性)。

从技术上讲,您根本不需要 tsconfig.app.json。如果删除它,则必须将 "module": "esnext" 放在 tsconfig.json 中。如果保留在那里,它将优先于 tsconfig.json,因此您只需要在 tsconfig.app.json.

中添加 "module":"esnext"

我通过执行以下步骤解决了这个错误 步骤1: "module": "es2015" 到 "module": "AMD" 在 tsconfig.json

第 2 步: 在app根目录新建一个文件tsconfig.app.json,复制Tony Ngo的代码粘贴进去,问题就解决了。

我的 angular 版本是 8.2,我通过将 "module": "es2015" 更改为 "module": "es2020"

来修复它

我只是通过添加解决了这个问题 “包括”:[“src/**/*.ts”] 在我的 tsconfig.app.json 文件中。

如果您使用的是 Ionic 框架并且 VSCode 您需要更新您的 Typescript IDE 版本(> 4)!

只需通过以下命令更新 angular 版本。错误将消失。

ng update @angular/core @angular/cli --next

之后,更改 tsconfig.json 文件中的目标和模块

"target": "esnext",
"module": "esnext",

我在使用 angular 13 时遇到了这个问题,我注意到有些服务有这个问题而有些则没有,区别是

@import { Injectable } from '@angular/core/';

虽然这在 angular 9 上完美编译没有任何问题,但修复是删除末尾的 / 成为'

@import { Injectable } from '@angular/core';