The cause of this error
the moment() method without importing them into the script. Or you did not install the module moment in the terminal command on your project.
Before calling the
moment() method in your script, you must make sure that the module moment is already installed in your project and import it into your script.
In this example, we pass the time string and date format into the
moment() function but do not install the module moment first. This is the main cause of this error.
Let’s see the code example below.
// This is the cause of this error, use the moment() function but not import it const mDate = moment("24-12-2022", "DD-MM-YYYY"); const dateObject = mDate.toDate(); console.log(dateObject);
The error will show if you try to run this code.
Error: Cannot find module ‘moment’
To Deal with the “Cannot find module ‘moment’” Error
The “Cannot find module moment” error can be solved by following the steps.
- Installing the module in your project
- Import the moment module in your script before calling it out
Install the moment module.
npm install moment
Then, we use the
require('moment') to import and use the moment module in our project. In this example, we will use the moment() method to format the date to DD-MM-YYYY, Then call the toDate() method to convert it to a Date() object as a string, and print out the result on the console.
See the example below.
// Import the moment module import moment from "moment"; // Now you can using the moment() method const mDate = moment("24-12-2022", "DD-MM-YYYY"); const dateObject = mDate.toDate(); console.log(dateObject);
Sat Dec 24 2022 00:00:00 GMT+0700 (Indochina Time)
Thank you for reading!
Name of the university: HUSC