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

如何在Vite + React项目中实现构建日期自动注入?

在React+Vite项目中自动替换构建日期

步骤1:修改index.html

在项目根目录的index.html文件中,添加需要的日志代码:

<script>console.log(__BUILD_DATE__);</script>

步骤2:配置Vite实现占位符替换

打开vite.config.js(TypeScript项目对应vite.config.ts),通过Vite的define配置项完成构建时的变量替换:

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

export default defineConfig({
  plugins: [react()],
  define: {
    // 用JSON.stringify确保生成合法的字符串格式
    __BUILD_DATE__: JSON.stringify(new Date().toLocaleString())
  }
})

可选:区分开发/生产环境

如果需要在开发环境和生产环境显示不同内容,可通过环境模式判断:

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

export default defineConfig(({ mode }) => {
  return {
    plugins: [react()],
    define: {
      __BUILD_DATE__: mode === 'production'
        ? JSON.stringify(new Date().toLocaleString())
        : JSON.stringify('开发环境')
    }
  }
})

你可以根据需求调整时间格式,比如用new Date().toISOString()获取标准ISO格式的时间字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:40:48