首页 文章

为什么我不能在我的TypeScript React本机项目中使用moment作为导入?

提问于
浏览
0

我想在使用TypeScript的ReactNative组件中使用MomentJS . 我的项目配置为从node_modules目录中提取library's d.ts file .

这是我导入库并使用它的方式:

import * as moment from "moment";
const time = moment();

我的打字稿编译,但当我运行应用程序ReactNative错误时:

ReactNative error

这是我的tsconfig.json文件:

{
  "compilerOptions": {
    "target": "es6",
    "moduleResolution": "node",
    "jsx": "react",
    "outDir": "build/",
    "sourceMap": true,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

如果我将我的tsconfig'target'更改为es5,我会遇到许多其他模块的问题 .

我认为这与this question有关,但我按照该问题答案的建议做了 .

1 回答

  • 1

    引用@DavidD's comment in the linked answer

    如果你在上面的语法之上使用babel,请小心,babel会阻止函数moment()按预期工作,因为它与规范相关联 . 您可以在tsconfig.json中添加“allowSyntheticDefaultImports”:true以允许从“时刻”导入时刻;不再抛出错误 .

    根本问题是 moment 将一个函数导出为默认函数,但是当使用Babel时(因为你在React Native中),这将被Babel包装在一个对象中 .

    我不确定TypeScript是否知道这种包装或者是否需要更新momentjs的定义 .

相关问题