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

React构建后为静态资源添加时间戳参数的Shell实现

给React构建后的静态资源链接添加时间戳参数

实现步骤

  1. 完成React项目构建
    先执行标准构建命令生成build目录:

    npm run build
    # 或者使用yarn
    yarn build
    
  2. 编写Shell脚本自动添加时间戳
    创建一个Shell脚本(比如命名为add-timestamp.sh),内容如下:

    # 生成格式为YYYY-MM-DD-HH:MM:SS的时间戳
    VERSION=$(date +%Y-%m-%d)-$(date +%T)
    
    # 给CSS资源链接追加?time=时间戳参数
    sed -i -- "s/\(href=\"\/static\/css\/.*\.css\"\)/\1?time=$VERSION/g" build/index.html
    
    # 给JS资源链接追加?time=时间戳参数
    sed -i -- "s/\(src=\"\/static\/js\/.*\.js\"\)/\1?time=$VERSION/g" build/index.html
    
  3. 执行脚本
    给脚本添加执行权限并运行:

    chmod +x add-timestamp.sh
    ./add-timestamp.sh
    

效果示例

处理前:

<link href="/static/css/main.3678df32.css" rel="stylesheet">
<script src="/static/js/main.987abc12.js"></script>

处理后:

<link href="/static/css/main.3678df32.css?time=2023-03-06-16:05:43" rel="stylesheet">
<script src="/static/js/main.987abc12.js?time=2023-03-06-16:05:43"></script>

注意事项

  • 若在macOS环境下,sed命令语法略有差异,需将-i --替换为-i '':
    sed -i '' "s/\(href=\"\/static\/css\/.*\.css\"\)/\1?time=$VERSION/g" build/index.html
    sed -i '' "s/\(src=\"\/static\/js\/.*\.js\"\)/\1?time=$VERSION/g" build/index.html
    
  • 可将脚本整合到package.json的scripts中,实现构建后自动执行:
    "scripts": {
      "build": "react-scripts build && ./add-timestamp.sh"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:35:18