You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-live-clock与react-moment在Vite项目中遇TypeError问题求助

React+Vite+TS项目中react-live-clock导致浏览器报错无法显示页面

问题详情

用Vite搭建React+TS项目后,引入react-live-clock组件,开发服务启动无报错,但浏览器页面无法渲染,控制台抛出如下错误:

index.js:11 Uncaught TypeError: Cannot set properties of undefined (setting 'format')
    at F (index.js:11:13125)
    at Object.l (index.js:11:13816)
    at Object.<anonymous> (index.js:11:13871)
    at n (index.js:1:447)
    at Module.<anonymous> (index.js:11:14085)
    at n (index.js:1:447)
    at index.js:1:1246
    at index.js:1:1254
    at index.js:1:81
    at node_modules/react-moment/dist/index.js (index.js:1:310)

项目依赖配置:

{
  "name": "react-ts",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@fontsource/roboto": "^5.0.5",
    "@mui/icons-material": "^5.14.1",
    "@mui/material": "^5.14.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-live-clock": "^5.10.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.14",
    "@types/react-dom": "^18.2.6",
    "@typescript-eslint/eslint-plugin": "^5.62.0",
    "@typescript-eslint/parser": "^5.61.0",
    "@vitejs/plugin-react": "^4.0.1",
    "typescript": "^5.1.6",
    "vite": "^4.4.0"
  }
}

组件实现代码:

import { Box, Typography, Paper } from '@mui/material'
import Clock from 'react-live-clock';

function LiveClock() {
  return (
    <>
      <Box p={1}>
        <Paper elevation={3}>
          <Box p={2}>
            <Typography variant="h5">Formulario de Cronometraje</Typography>
            <Clock />
          </Box>
        </Paper>
      </Box>
    </>
  )
}

解决方案

1. 手动安装moment依赖

react-live-clock依赖react-moment,而react-moment又依赖moment,但部分版本的react-moment未正确声明peer依赖,导致ES模块环境下(Vite默认使用ES模块)moment未被自动安装。执行以下命令安装:

npm install moment

2. 配置Vite优化moment模块

如果安装后仍报错,是因为moment是CommonJS模块,Vite的依赖预构建可能未正确处理。修改vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    include: ['moment']
  }
})

3. 降级react-live-clock版本

若以上方法无效,尝试降级到兼容性更好的版本:

npm install react-live-clock@5.9.0

原因说明

报错指向react-moment的编译文件,本质是react-moment尝试修改moment对象的format属性时,moment为undefined。这是ES模块环境与CommonJS模块(moment)的兼容问题,要么依赖缺失,要么Vite预构建未正确处理该模块。

内容的提问来源于stack exchange,提问作者Lautaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:34:49