Reputation: 2720
I want to use MomentJS in my ReactNative component using TypeScript. My project is configured to pull in the library's d.ts file from the node_modules directory.
This is how I am importing the library and using it:
import * as moment from "moment";
const time = moment();
My typescript compiles but when I run the app ReactNative errors as so:
This is my tsconfig.json file:
{
"compilerOptions": {
"target": "es6",
"moduleResolution": "node",
"jsx": "react",
"outDir": "build/",
"sourceMap": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
If I change my tsconfig 'target' to es5 I have problems with a number of other modules.
I think it is related to this question but I am doing as suggested in that question's answer.
Upvotes: 0
Views: 683
Reputation: 160043
Quoting from @DavidD's comment in the linked answer:
Be careful if you use babel on top of the above syntax, babel will prevent the function
moment()
from work as expected, due to how it associates with the spec. You can add"allowSyntheticDefaultImports": true
to your tsconfig.json to allowimport moment from "moment";
to no longer throw an error.
The underlying issue is that moment
exports a function as the default, but when using Babel (as you are in React Native) this will get wrapped in an object by Babel.
I'm not sure if TypeScript is aware of this wrapping or if the definitions for momentjs need an update.
Upvotes: 1