【问题标题】:typescript duplicate import of 'moment'打字稿重复导入“时刻”
【发布时间】:2020-03-06 03:45:34
【问题描述】:

我在 typescript/React 项目中使用 momentjs。目前我在文件顶部有这些行:

import * as moment from 'moment';
import { Moment } from 'moment';

其中Moment 是矩的类型,moment 是矩对象本身,例如:

let m: Moment = moment.now();

现在我的 typescript linter 抱怨:Multiple imports from 'moment' can be combined into one. (no-duplicate-imports)tslint(1)

但是我不知道该怎么做。不知道如何在同一导入行中使用 *Moment...

【问题讨论】:

  • Moment 不应作为命名空间 (* as) 导入。它应该作为默认导出导入。 import moment from 'moment'; 然后你可以写import moment, {Moment} from 'moment';。始终在 tsconfig.json 中设置 esModuleInterop: true
  • 谢谢 - 成功了。如果您愿意,将接受它作为答案。

标签: typescript momentjs


【解决方案1】:

按照 Aluan Haddad 的建议,尝试将时刻导入为默认导出。然后您的导入将在下面使用看起来很好

import moment, {Moment} from 'moment';

在你的 tsconfig.json 中,你应该有 allowSyntheticDefaultImports :true

【讨论】:

  • 没错,但是根据您的模块加载器/捆绑器,您还需要指定"esModuleInterop": true。这实际上隐含地设置了"allowSyntheticDefaultImports": true,但明确表示并没有什么坏处。前者只影响类型检查,所以你的模块工具必须做这个工作,而后者实际上是合成默认的
猜你喜欢
  • 2018-09-01
  • 1970-01-01
  • 2020-04-19
  • 2023-02-09
  • 2012-12-26
  • 1970-01-01
  • 2016-06-12
  • 2016-01-24
相关资源
最近更新 更多