Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import moment.js in ES6 using npm?

Tags:

I am using angular js and nodejs along with ES6. I want to import the moment.js in the angular js code. I did 'npm install moment --save'

Now I am able to see moment.js file in moment folder which is inside node modules.

and in my app.js file I have wriiten like this

'import moment from 'moment'; 

But if search something with date range It is showing error in console. Can anybody help me how to do this..?

like image 294
Santhosh Aineri Avatar asked Apr 07 '16 12:04

Santhosh Aineri


People also ask

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.

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 .


2 Answers

Currently, to use ES6 module syntax, you need to use a transpiler e.g. Babel, since node.js and most browsers do not yet support ES6 module syntax.

Babel and webpack are great for this. Here is a nice example:

Once you have it configured properly, you invoke moment as such:

import moment from 'moment'; console.log(moment.now()); 
like image 102
cmd Avatar answered Sep 20 '22 12:09

cmd


Since version 2.10.0 moment is written in ES6 :

import moment from './node_modules/moment/src/moment'; // Note the 'src/' to import the ES6 version and not the CJS build 

However for now it seems there is no way to import only a subset of functions, you have to import the whole thing.

like image 29
flawyte Avatar answered Sep 19 '22 12:09

flawyte