Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing moment into TypeScript project

I am trying to use moment in my TypeScript project but when I use the line,

import moment from 'moment';

I get the error:

'node_modules/moment/moment' has no default export.

I have also tried,

import moment from 'moment/src/moment';

but then I get the error:

'Cannot find module moment/src/moment'.

Does anybody know a way of doing this? Thanks.

like image 994
Yulric Sequeira Avatar asked Apr 27 '16 14:04

Yulric Sequeira


People also ask

How do I import a moment in TypeScript?

To import moment. js with TypeScript, we can import the whole package with import . import * as moment from "moment"; to import the 'moment' module as moment .

How do I use moment-timezone in TypeScript?

Use Typescript @types packages and import it via import * as moment from 'moment-timezone'; You can use all moment methods and member vars as moment-timezone exports them. Show activity on this post. Show activity on this post.

Is Momentjs deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.


2 Answers

The correct syntax is:

import * as moment from 'moment';
like image 81
rgvassar Avatar answered Nov 03 '22 00:11

rgvassar


I had the same issue and solved the problem in my project by adding allowSyntheticDefaultImports: true in compilerOptions in my tsconfig.json file and then I used the syntax

import moment from 'moment';

Reference: "https://momentjs.com/docs/#/use-it/typescript/"

like image 39
Tim K. Avatar answered Nov 03 '22 01:11

Tim K.