无法在 Angular 9 中进行默认导入

Geo*_*tan 11 javascript node.js typescript angular

我通过添加此属性更改了tsconfig.json

"esModuleInterop": true, "allowSyntheticDefaultImports": true,

为了能够导入 npm 包 import * as ms from "ms";

但我仍然收到这个错误

This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

更新:

如果我更改为import ms from "ms",那么它可以与编译器一起正常工作,但不能与 VSCode linter 一起使用,并且错误是

 can only be default-imported using the 'allowSyntheticDefaultImports' flagts(1259)
index.d.ts(25, 1): This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.
Run Code Online (Sandbox Code Playgroud)

正如我所说,现在正在运行,但 VSCode 有问题。

Pok*_*Art 86

"allowSyntheticDefaultImports": true

该标志解决了问题,但应将其添加到tsconfig.json 的compilerOptions部分

  • 这个解决方案在 NestJS 上对我有用! (3认同)

Eve*_*ver 16

你可以做这样的事情

import * as printJS from 'print-js'
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 6

如果您在尝试将 localforage 导入 angular 9 时遇到此错误,我使用了这个(Angular 9.1.12,Typescript 3.9.6):

npm 安装本地草料

// tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  },
   "esModuleInterop": true, <----------------------------add this
   "allowSyntheticDefaultImports": true <----------------------------and this
}
Run Code Online (Sandbox Code Playgroud)

// 任何组件或服务

import * as localforage from 'localforage';

constructor() {
    localforage.setItem('localforage', 'localforage value');
    setTimeout(() => {
      localforage.getItem('localforage').then((e) => {
       console.log(e);
      });
    }, 5000);
    setTimeout( async () => {
      const RES = await localforage.getItem('localforage');
      console.log('RES', RES);
    }, 10000);
  }
Run Code Online (Sandbox Code Playgroud)

  • 在 //tsconfig.ts 中的 compilerOptions 下移动后工作,如下所示 "compilerOptions": { "allowSyntheticDefaultImports":true, "esModuleInterop": true} (3认同)
  • 小心添加 `"esModuleInterop": true`,它可能会破坏 `import * as moment from 'moment';` 等内容 (2认同)

Luc*_*usa 4

问题在于包如何声明导出,您仍然可以使用默认导入来导入:

import ms from "ms";
Run Code Online (Sandbox Code Playgroud)