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

时间:2020-03-30 17:16:18

标签: javascript node.js angular typescript

我通过添加此属性更改了 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.

我想念什么?

更新

如果我使用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.

正如我现在所说的,但是VSCode有问题。

4 个答案:

答案 0 :(得分:15)

你可以做这样的事情

import * as printJS from 'print-js'

答案 1 :(得分:1)

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

import ms from "ms";

答案 2 :(得分:1)

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

npm安装localforage

// 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
}

//任何组件或服务

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);
  }

答案 3 :(得分:0)

有错误信息

<块引用>

此模块使用“export =”声明,并且只能在使用“allowSyntheticDefaultImports”标志时与默认导入一起使用。

关于 Angular 组件的打字稿导入规则:

import { something } from 'amodule';

在 node_modules/@types/amodule/index.d.ts 中,我找到了这段代码:

declare module 'amodule' {
   export = something;
}

并将其更改为:

declare module 'amodule' {
    export default something;
}

angular 组件中的导入规则改为:

 import something from 'amodule';

错误信息消失,导入的模块可以正常使用。