Skip to content

MomentJS - 环境搭建

现代日期/时间处理:设置 Moment.js

Section titled “现代日期/时间处理:设置 Moment.js”

在使用 Moment.js 之前,你需要将其包含到你的项目中。以下是现代 Web 开发中常用的几种方法。

提示: Moment.js 处于维护模式。虽然设置很简单,但考虑到 Moment.js 的 bundle size(打包大小)和 mutability(可变性),对于新项目,请考虑 Day.js、date-fns 或原生 API 等替代方案。详情参见 ‘Overview’ 部分。

方法 1:使用 npm 或 Yarn(推荐用于构建流程)

Section titled “方法 1:使用 npm 或 Yarn(推荐用于构建流程)”

如果你正在使用 Node.js 或前端构建系统(如 Webpack、Rollup、Parcel、Vite),通过包管理器安装是标准做法。

在你的项目目录中打开终端并运行:

# 使用 npm
npm install moment
# 或使用 Yarn
yarn add moment

这将下载 Moment.js 并将其添加到项目的 node_modules 文件夹,同时更新你的 package.json 文件。

然后你可以将其导入到你的 JavaScript 或 TypeScript 文件中:

// ES6 Import (在现代前端和 Node.js 中常用)
import moment from 'moment';
// CommonJS Require (传统的 Node.js)
const moment = require('moment');
// --- 使用示例 ---
const today = moment();
console.log(today.format('YYYY-MM-DD')); // 输出当前日期

要使用这种方法加载特定的 locale,请单独导入它们(参见 ‘Internationalization’ 部分)。

import moment from 'moment';
import 'moment/locale/es'; // 导入西班牙语 locale 数据
moment.locale('es');
console.log(moment().format('LL')); // 输出示例:26 de octubre de 2023

方法 2:使用 CDN 或下载文件(浏览器端)

Section titled “方法 2:使用 CDN 或下载文件(浏览器端)”

对于简单的 HTML 页面或无需构建系统的快速测试,你可以使用 <script> 标签直接包含 Moment.js。

使用像 cdnjs 或 jsDelivr 这样的 CDN 通常是最简单的方法:

<!DOCTYPE html>
<html>
<head>
<title>Moment.js via CDN</title>
<!-- 从 cdnjs.com 或 jsdelivr.com 获取最新版本 URL -->
<!-- 使用 jsDelivr 的示例 -->
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
<!-- 可选:包含 locales(文件更大)-->
<!-- <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>
  1. 访问 Moment.js 官方网站 (https://momentjs.com/) 并下载 moment.min.js 文件(如果需要打包所有 locale,也可以下载 moment-with-locales.min.js)。

  2. 将下载的文件放置到你的项目目录中(例如,放在 js/ 文件夹下)。

  3. 在你的 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>

方法 3:在 Node.js 中使用(脚本)

Section titled “方法 3:在 Node.js 中使用(脚本)”

如果你通过 npm 为 Node.js 脚本(非 Web 项目)安装了 Moment.js,你只需使用 require 导入它即可:

  1. 确保你已在项目文件夹中运行 npm install moment。

  2. 创建一个 JavaScript 文件(例如 test-moment.js):

const moment = require('moment');
const now = moment();
console.log(`Node.js Script Time: ${now.toString()}`);
// locale 示例(确保已加载)
try {
require('moment/locale/fr');
moment.locale('fr');
console.log(`En Français: ${now.format('LLLL')}`);
} catch (e) {
console.warn('未找到法语 locale 或加载错误。');
}
console.log(`Duration 示例: ${moment.duration(2, 'hours').humanize()}`);
  1. 从终端运行脚本:
node test-moment.js

选择最适合你的项目结构和构建流程的设置方法。