Skip to content

MomentJS - 简介

本节介绍如何在不同的 JavaScript 环境和构建系统中集成 Moment.js,重点关注现代实践。

与模块打包工具(Webpack, Rollup, Parcel, Vite)一起使用 Moment.js

Section titled “与模块打包工具(Webpack, Rollup, Parcel, Vite)一起使用 Moment.js”

使用现代构建设置时,通常通过 npm/yarn 安装 Moment.js 并导入它。

# 1. 安装
npm install moment
# 或者
yarn add moment
# 2. 在你的 JS/TS 文件中导入
import moment from 'moment';
// 可选:导入特定语言环境以减小打包体积
import 'moment/locale/fr';
import 'moment/locale/de';
// 使用示例
function displayTime(locale) {
moment.locale(locale);
console.log(`Locale [${locale}]: ${moment().format('LLLL')}`);
}
displayTime('en'); // 默认英语
displayTime('fr'); // 法语
displayTime('de'); // 德语

您的打包工具会处理将 Moment.js 和导入的语言环境打包到最终的应用程序 bundle 中。仅导入所需的语言环境对于性能至关重要。

Moment.js 通常与 TypeScript 配合良好。类型定义通常已包含或通过 @types/moment 提供。

  1. 安装 Moment.js 并可能需要安装类型定义:
npm install moment
# 或者:yarn add moment
# 类型定义可能已打包,但如果需要:
npm install --save-dev @types/moment
# 或者:yarn add --dev @types/moment
  1. 在您的 .ts 文件中导入并使用:
import moment, { Moment } from 'moment'; // 如果需要,导入 Moment 类型
import 'moment/locale/it'; // 导入意大利语语言环境
const now: Moment = moment(); // 显式类型声明
const futureDate = moment().add(7, 'days');
function getFormattedDate(date: Moment | string, locale: string): string {
// 如果需要,使用 moment.isMoment 进行类型检查
const momentDate = moment(date);
if (!momentDate.isValid()) {
return 'Invalid Date';
}
return momentDate.locale(locale).format('LL');
}
console.log(getFormattedDate(now, 'en')); // 例如:October 26, 2023
console.log(getFormattedDate(futureDate, 'it')); // 例如:2 novembre 2023
console.log(getFormattedDate('Not a date', 'en')); // 输出:Invalid Date

确保您的 tsconfig.json 配置正确(例如,"moduleResolution": "node"、"esModuleInterop": true 可能会有帮助)。

旧版用法:在 RequireJS (AMD) 中使用 Moment.js

Section titled “旧版用法:在 RequireJS (AMD) 中使用 Moment.js”

虽然在新项目中不太常见,但在较旧的代码库中,你可能会遇到使用异步模块定义(AMD)加载器(如 RequireJS)来使用 Moment.js 的情况。

设置通常包括:

  1. 配置 (main.js 或类似文件): 定义 Moment.js 库的路径。
require.config({
paths: {
'moment': 'path/to/moment.min' // 无需 .js 扩展名
// 如果需要,添加语言环境文件的路径,例如:
// 'moment-fr': 'path/to/locale/fr'
}
// 旧版本或插件可能需要 Shim 配置
});
  1. 用法: 使用 require 或 define 作为依赖加载 Moment.js。
require(['moment'], function(moment) {
// 现在可以在这里使用 Moment 对象
const now = moment();
console.log('RequireJS Moment:', now.format());
// 加载语言环境示例(如果已配置)
// require(['moment', 'moment-fr'], function(moment) { // 注意:如果命名正确,Moment 会自动加载语言环境
// moment.locale('fr');
// console.log(moment().format('LL'));
// });
});

如果处理此类设置,请参考 RequireJS 文档和特定 Moment.js 版本的说明以了解兼容性细节。