Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use moment.js library in angular 2 typescript app?

I tried to use it with typescript bindings:

npm install moment --save typings install moment --ambient -- save 

test.ts:

import {moment} from 'moment/moment'; 

And without:

npm install moment --save 

test.ts:

var moment = require('moment/moment'); 

But when I call moment.format(), I get an error. Should be simple, can anybody provide a command line/import combination that would work?

like image 219
Sergey Aldoukhov Avatar asked Feb 03 '16 00:02

Sergey Aldoukhov


People also ask

Can I use MomentJS in angular?

The moment object lives on window in the browser. Therefor it is not correct to import it in your angular2 application. Instead include the <script> tag in your html that will load the moment. js file.

What is Moment library in angular?

moment. js is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates. Two simple steps require to add moment js in Angular 8 applications.

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.

Is MomentJS still used?

Conclusion. MomentJS isn't completely gone yet. But on their website they suggest you look beyond Moment unless you fall into specific usecases. Luxon seems to be the biggest replacement for Moment that is futureproof for now.


1 Answers

Update April 2017:

As of version 2.13.0, Moment includes a typescript definition file. https://momentjs.com/docs/#/use-it/typescript/

Just install it with npm, in your console type

npm install --save moment 

And then in your Angular app, import is as easy as this:

import * as moment from 'moment'; 

That's it, you get full Typescript support!

Bonus edit: To type a variable or property as Moment in Typescript you can do this e.g.:

let myMoment: moment.Moment = moment("someDate"); 
like image 178
Hinrich Avatar answered Sep 22 '22 22:09

Hinrich