How to import moment.js in ES6 using npm?

59,686

Solution 1

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());

Solution 2

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.

Solution 3

The option, that worked for me is:

import * as moment from 'moment';

Solution 4

This is what you are looking.

import moment from 'moment'
import it from 'moment/locale/it'
import { utc } from 'moment'
moment.locale('it')

You can read the related issue here. https://github.com/moment/moment/issues/2608

Solution 5

the code you written wont work.its not

//wont work
'import moment from moment'; this is wrong.
//this will work
import moment from 'moment';
or
import 'moment';

if these wont work.then try it using web-pack to expose moment to globally.

Share:
59,686

Related videos on Youtube

Santhosh Aineri
Author by

Santhosh Aineri

Updated on July 22, 2022

Comments

  • Santhosh Aineri
    Santhosh Aineri almost 2 years

    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..?

    • Mukesh Sharma
      Mukesh Sharma about 8 years
      Is app.js node.js file ? If yes, then use var moment = require('moment');
    • Santhosh Aineri
      Santhosh Aineri about 8 years
      No Mukesh. I am talking about app.js in angular
    • Felix Kling
      Felix Kling about 8 years
      Are you going to tell us what the error is?
  • Santhosh Aineri
    Santhosh Aineri about 8 years
    Hi Anlainlb. I am using es6 along with webpack. If I use node modules , webpack can build the front end code. So I want to do in that way
  • atilkan
    atilkan over 4 years
    It is a typo. Not relevant to actual question.
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.