How to import moment.js in ES6 using npm?
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.
Related videos on Youtube
Santhosh Aineri
Updated on July 22, 2022Comments
-
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 about 8 yearsIs
app.js
node.js file ? If yes, then usevar moment = require('moment');
-
Santhosh Aineri about 8 yearsNo Mukesh. I am talking about app.js in angular
-
Felix Kling about 8 yearsAre you going to tell us what the error is?
-
-
Santhosh Aineri about 8 yearsHi 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 over 4 yearsIt is a typo. Not relevant to actual question.
-
Admin over 2 yearsYour 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.