Solve - ReferenceError moment is not defined in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Table of Contents #

  1. Solve - ReferenceError moment is not defined in Node.js
  2. Solve - ReferenceError moment is not defined in the Browser

Solve - ReferenceError moment is not defined #

The "ReferenceError: moment is not defined" error occurs for 2 reasons:

  1. Not installing and importing the moment package in a Node.js application.
  2. Not loading the moment script before your code in the browser.

referenceerror moment is not defined

Solve - ReferenceError moment is not defined in Node.js #

To solve the "ReferenceError: moment is not defined" error in Node.js, make sure to install and import the moment package before using it.

shell
npm install moment
Note that if your project does not have a package.json file, you have to create one first with the npm init -y command.

Now you can use the moment library in your code.

index.js
import moment from 'moment'; console.log(moment().format());

We used the ES6 module import/export syntax. If you're using an older version of Node.js, you can use the require() syntax to achieve the same result.

index.js
const moment = require('moment'); console.log(moment().format());

Solve - ReferenceError moment is not defined in the Browser #

To solve the "ReferenceError: moment is not defined" error in the browser, make sure to load the script for the moment library before running your JavaScript code.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ๐Ÿ‘‡๏ธ Your HTML code HERE ๐Ÿ‘‡๏ธ --> <!-- โœ… Load the moment library โœ… --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> <!-- โœ… Run your JavaScript code --> <script type="module" src="index.js"></script> </body> </html>

Note that we loaded the JavaScript code for the moment module before running our JavaScript code. This way, we can ensure that the moment variable will be available in our index.js file.

index.js
console.log(moment().format());

In our index.js file we can directly use the moment library without having to import it.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee