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

时间:2019-05-30 09:45:53

标签: angular typescript module angular8

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

我尝试了角度升级指南中的选项

进行以下更改:

之前

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

之后

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

错误TS1323:仅当'--module'标志为   'commonjs'或'esNext'。

9 个答案:

答案 0 :(得分:8)

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

{
  "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"
  ]
}

答案 1 :(得分:2)

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

答案 2 :(得分:1)

只需添加到@Tony的anwser中,您可能还需要在tsconfig.app.json中执行相同的操作(更改为“ module”:“ esnext”)。在我的情况下,tsconfig.json已经使用esnext作为模块,但是tsconfig.app.json仍使用es2015,这导致了此错误。

答案 3 :(得分:1)

我认为执行此操作的正确方法是调整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 工作区的根目录下。 tsconfig.app.json存在,因此,如果要构建其中包含多个个应用程序的Angular工作区,则可以为每个应用程序分别调整Typescript配置,而不必编写在两个应用程序之间重叠的冗余配置属性。应用程序(因此具有extends属性)。

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

答案 4 :(得分:0)

我通过执行以下步骤来解决此错误 第1步: “模块”:“ es2015”为 tsconfig.json中的“ module”:“ AMD”

步骤2: 在应用程序根目录中创建一个新文件tsconfig.app.json,复制Tony Ngo的代码并粘贴到其中,即可解决此问题。

答案 5 :(得分:0)

我的角度版本是8.2,我通过将“ module”:“ es2015”更改为“ module”:“ es2020”来解决了该问题

答案 6 :(得分:0)

我只能通过添加来解决此问题 “ include”:[“ src / ** / *。ts”] 在我的tsconfig.app.json文件中。

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

vue.config.js

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

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