MomentJS - Environment Setup
Modern Date/Time: Setting Up Moment.js
Section titled “Modern Date/Time: Setting Up Moment.js”Before using Moment.js, you need to include it in your project. Here are the common methods for modern web development.
Reminder: Moment.js is in maintenance mode. While setup is straightforward, consider alternatives like Day.js, date-fns, or native APIs for new projects due to Moment.js’s bundle size and mutability. See the ‘Overview’ section.
Method 1: Using npm or Yarn (Recommended for Build Processes)
Section titled “Method 1: Using npm or Yarn (Recommended for Build Processes)”If you’re using Node.js or a front-end build system (like Webpack, Rollup, Parcel, Vite), installing via a package manager is the standard approach.
Open your terminal in your project directory and run:
# Using npmnpm install moment
# Or using Yarnyarn add momentThis will download and add Moment.js to your project’s node_modules folder and update your package.json file.
You can then import it into your JavaScript or TypeScript files:
// ES6 Import (common in modern front-end and Node.js)import moment from 'moment';
// CommonJS Require (traditional Node.js)const moment = require('moment');
// --- Usage Example ---const today = moment();console.log(today.format('YYYY-MM-DD')); // Outputs the current dateTo use specific locales with this method, import them separately (see ‘Internationalization’ section).
import moment from 'moment';import 'moment/locale/es'; // Import Spanish locale data
moment.locale('es');console.log(moment().format('LL')); // Output: e.g., 26 de octubre de 2023Method 2: Using a CDN or Downloaded File (Browser)
Section titled “Method 2: Using a CDN or Downloaded File (Browser)”For simple HTML pages or quick tests without a build system, you can include Moment.js directly using a <script> tag.
Option A: Content Delivery Network (CDN)
Section titled “Option A: Content Delivery Network (CDN)”Using a CDN like cdnjs or jsDelivr is often easiest:
<!DOCTYPE html><html><head> <title>Moment.js via CDN</title> <!-- Get the latest version URL from cdnjs.com or jsdelivr.com --> <!-- Example using jsDelivr --> <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script> <!-- Optional: Include locales (larger file) --> <!-- <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/min/moment-with-locales.min.js"></script> --></head><body> <h1>Moment.js Test</h1> <div id="output"></div>
<script> const now = moment(); document.getElementById('output').textContent = `Current Date: ${now.format('MMMM Do YYYY')}`; </script></body></html>Option B: Download and Host Locally
Section titled “Option B: Download and Host Locally”-
Visit the official Moment.js website (https://momentjs.com/) and download the
moment.min.jsfile (and potentiallymoment-with-locales.min.jsif you need all locales bundled). -
Place the downloaded file(s) in your project directory (e.g., in a
js/folder). -
Include it in your HTML:
<!DOCTYPE html><html><head> <title>Moment.js Locally</title> <script src="js/moment.min.js"></script></head><body> <h1>Moment.js Test</h1> <div id="output"></div>
<script> const now = moment(); document.getElementById('output').textContent = `Current Date: ${now.format('YYYY/MM/DD')}`; </script></body></html>Method 3: Using in Node.js (Scripting)
Section titled “Method 3: Using in Node.js (Scripting)”If you installed Moment.js via npm for a Node.js script (not a web project), you just need to require it:
-
Make sure you’ve run
npm install momentin your project folder. -
Create a JavaScript file (e.g.,
test-moment.js):
const moment = require('moment');
const now = moment();console.log(`Node.js Script Time: ${now.toString()}`);
// Example with locale (ensure it's loaded)try { require('moment/locale/fr'); moment.locale('fr'); console.log(`En Français: ${now.format('LLLL')}`);} catch (e) { console.warn('French locale not found or error loading it.');}
console.log(`Duration example: ${moment.duration(2, 'hours').humanize()}`);- Run the script from your terminal:
node test-moment.jsChoose the setup method that best fits your project structure and build process.