前端react框架实现打包时间动态加入配置展示在指定页面

注意:

当前方法特定为 create-react-app 构建框架,其他的构建流程不同,不能直接照搬 react-scripts 的方式。

✅ 目标:

在 React 打包(build)时,自动将当前时间写入代码中某个变量或 console.log 中,例如:

console.log('Build Time: 2025-06-24 15:09');

✅ 实现思路:

React 默认使用 create-react-app(CRA),它基于 Webpack 构建系统。我们可以通过以下方式实现:

方法一:使用环境变量 + 构建脚本生成时间戳

步骤 1:创建一个 build.js 脚本,在打包前生成时间戳

在项目根目录下新建一个文件:build.js

// build.js
const fs = require('fs');
const path = require('path');

const now = new Date();
const formattedTime = now.toLocaleString('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false,
}).replace(/\//g, '-'); // 格式:2025-06-24 15:09:00

const content = `export const BUILD_TIME = '${formattedTime}';`;

fs.writeFileSync(path.resolve(__dirname, 'src/buildTime.js'), content);

这个脚本会在 src/ 下生成一个 buildTime.js 文件,内容类似:

export const BUILD_TIME = '2025-06-24 15:09';

步骤 2:在你的 React 项目中引用这个时间戳

比如在 index.js 或任意组件中引入并打印:

import { BUILD_TIME } from './buildTime';

console.log(`Build Time: ${BUILD_TIME}`);

步骤 3:修改 package.json 中的 build 命令
"scripts": {
  "start": "react-scripts start",
  "build": "node build.js && react-scripts build",
  "test": "react-scripts test"
}

这样每次执行 npm run build 时,都会先运行 build.js,自动生成最新的打包时间。


✅ 最终效果:

打包后输出如下日志(在浏览器控制台可见):

Build Time: 2025-06-24 15:09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值