MomentJS - Introduction
Modern Date/Time: Integrating Moment.js
Section titled “Modern Date/Time: Integrating Moment.js”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. Installnpm install moment# oryarn add moment
# 2. Import in your JS/TS fileimport moment from 'moment';
// Optional: Import specific locales to keep bundle size downimport 'moment/locale/fr';import 'moment/locale/de';
// Example Usagefunction displayTime(locale) { moment.locale(locale); console.log(`Locale [${locale}]: ${moment().format('LLLL')}`);}
displayTime('en'); // Default EnglishdisplayTime('fr'); // FrenchdisplayTime('de'); // GermanYour bundler will handle packaging Moment.js and the imported locales into your final application bundle. Importing only needed locales is crucial for performance.
Using Moment.js with TypeScript
Section titled “Using Moment.js with TypeScript”Moment.js generally works well with TypeScript. Type definitions are usually included or available via @types/moment.
- 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- Import and use in your
.tsfile:
import moment, { Moment } from 'moment'; // Import Moment type if neededimport 'moment/locale/it'; // Import Italian locale
const now: Moment = moment(); // Explicit typingconst 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, 2023console.log(getFormattedDate(futureDate, 'it')); // e.g., 2 novembre 2023console.log(getFormattedDate('Not a date', 'en')); // Output: Invalid DateEnsure 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:
- Configuration (
main.jsor 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});- Usage: Use
requireordefineto 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.