首页 > 解决方案 > 错误 TS1192:模块 @types/lodash/index 没有默认导出

问题描述

Angular 6.x.x在我的项目中使用以下lodash依赖项。

  "dependencies": {
    "@angular/common": "6.0.9",
    "@angular/core": "6.0.9",
    ...
    "@types/lodash": "^4.14.114",
    ...
  },

以下两个导入都不适合我。

import _ from 'lodash';  

import * as _ from 'lodash';

标签: angularlodash

解决方案


简短的

解决方案是:

  1. 添加{"esModuleInterop": true}到您的.tsconfig
  2. 确保您已安装"@types/lodash"在您的devDependencies

推理

简而言之: 与 ES6 默认相比, Typescript 具有不同的默认import机制。

例如,您可以通过以下方式从模块中导入函数:

  1. 整体导入:

    import _ from 'lodash';
    const results = _.uniq([1, 1, 2, 3]);
    
  2. 只导入一部分:

    import {uniq} from 'lodash';
    const results = _.uniq([1, 1, 2, 3]);
    

但是,在 Typescript 中,它为您提供了一些语法糖2. Import a part,如下所示:

// This is valid in Typescript
import uniq from 'lodash';
const results = _.uniq([1, 1, 2, 3]);

这很好,但1 Import as a whole无法推断。通过添加esModuleInterop它可以使默认的 ES6 行为再次起作用。

在另一个线程中提到了更多细节: Is there a way to use --esModuleInterop in tsconfig 而不是一个标志?


推荐阅读