Skip to content

MomentJS - Introduction

This section covers integrating Moment.js within different JavaScript environments and build systems, focusing on modern practices.

Using Moment.js with Module Bundlers (Webpack, Rollup, Parcel, Vite)

Section titled “Using Moment.js with Module Bundlers (Webpack, Rollup, Parcel, Vite)”

When using a modern build setup, you typically install Moment.js via npm/yarn and import it.

# 1. Install
npm install moment
# or
yarn add moment
# 2. Import in your JS/TS file
import moment from 'moment';
// Optional: Import specific locales to keep bundle size down
import 'moment/locale/fr';
import 'moment/locale/de';
// Example Usage
function displayTime(locale) {
moment.locale(locale);
console.log(`Locale [${locale}]: ${moment().format('LLLL')}`);
}
displayTime('en'); // Default English
displayTime('fr'); // French
displayTime('de'); // German

Your bundler will handle packaging Moment.js and the imported locales into your final application bundle. Importing only needed locales is crucial for performance.

Moment.js generally works well with TypeScript. Type definitions are usually included or available via @types/moment.

  1. Install Moment.js and potentially types:
npm install moment
# Or: yarn add moment
# Types might be bundled, but if needed:
npm install --save-dev @types/moment
# Or: yarn add --dev @types/moment
  1. Import and use in your .ts file:
import moment, { Moment } from 'moment'; // Import Moment type if needed
import 'moment/locale/it'; // Import Italian locale
const now: Moment = moment(); // Explicit typing
const futureDate = moment().add(7, 'days');
function getFormattedDate(date: Moment | string, locale: string): string {
// Use moment.isMoment for type checking if needed
const momentDate = moment(date);
if (!momentDate.isValid()) {
return 'Invalid Date';
}
return momentDate.locale(locale).format('LL');
}
console.log(getFormattedDate(now, 'en')); // e.g., October 26, 2023
console.log(getFormattedDate(futureDate, 'it')); // e.g., 2 novembre 2023
console.log(getFormattedDate('Not a date', 'en')); // Output: Invalid Date

Ensure your tsconfig.json is configured correctly (e.g., "moduleResolution": "node", "esModuleInterop": true might be helpful).

Legacy: Using Moment.js with RequireJS (AMD)

Section titled “Legacy: Using Moment.js with RequireJS (AMD)”

While less common in new projects, you might encounter Moment.js used with asynchronous module definition (AMD) loaders like RequireJS in older codebases.

Setup typically involves:

  1. Configuration (main.js or similar): Define paths to the Moment.js library.
require.config({
paths: {
'moment': 'path/to/moment.min' // No .js extension
// Add paths for locale files if needed, e.g.:
// 'moment-fr': 'path/to/locale/fr'
}
// Shim configuration might be needed for older versions or plugins
});
  1. Usage: Use require or define to load Moment.js as a dependency.
require(['moment'], function(moment) {
// Moment is now available here
const now = moment();
console.log('RequireJS Moment:', now.format());
// Example loading locale (if configured)
// require(['moment', 'moment-fr'], function(moment) { // Note: Moment loads locale automatically if named correctly
// moment.locale('fr');
// console.log(moment().format('LL'));
// });
});

Refer to RequireJS documentation and specific Moment.js version notes for compatibility details if working with such setups.