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

Raj*_*dda 68 javascript module typescript angular angular8

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

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

进行了以下更改:

之前

    loadChildren: '../feature/path/sample- 
                         tage.module#SameTagModule'
Run Code Online (Sandbox Code Playgroud)

   loadChildren: () => import('../feature/path/sample- 
                      tags.module').then(m => m.CreateLinksModule)
Run Code Online (Sandbox Code Playgroud)

错误TS1323:仅当'--module'标志为'commonjs'或'esNext'时,才支持动态导入。

Ton*_*Ngo 116

您正在使用动态导入,因此必须像这样更改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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

  • @ranbuch,我遇到了同样的问题,但没有删除该行,我只是将其更改为 `"module": "esnext"` 。 (8认同)
  • 我必须从我的`tsconfig.app.json`文件中删除`“ module”:“ es2015”`行 (5认同)
  • ng new在默认情况下不使用它。有什么原因吗? (3认同)
  • 当我在 polyfills 中取消注释 IE11 部分时,它似乎在 Edge、Chrome、Firefox 和 IE11 中工作,所以我很高兴。 (2认同)

Tai*_*uan 36

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

  • 在 IDEA Intelij 中我遇到了同样的问题。您需要重新打开该项目。 (6认同)

Zac*_*zer 21

我认为这样做的正确方法是调整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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.app.json是特定于应用程序的 Typescript 配置文件,位于 Angular工作区的根目录下。的tsconfig.app.json存在使得如果你正在构建具有角的工作区的多个在它的应用程序,则可以分别调节打字稿配置为每个应用而无需编写,所述应用程序(因此之间重叠冗余配置属性extends属性)。

从技术上讲,您根本不需要tsconfig.app.json。如果删除它,则必须将其"module": "esnext"放入tsconfig.json. 如果你把它放在那里,它会优先于tsconfig.json,所以你只需要"module":"esnext"tsconfig.app.json.


Niz*_*Niz 13

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

  • 我们可以避免在两个文件中都添加“module”:“esnext”,我们可以把它放在 tsconfig.json 但不能放在 tsconfig.app.json 中,因为这已经扩展了 tsconfig.json。 (4认同)