React构建后为静态资源添加时间戳参数的Shell实现
给React构建后的静态资源链接添加时间戳参数
实现步骤
完成React项目构建
先执行标准构建命令生成build目录:npm run build # 或者使用yarn yarn build编写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执行脚本
给脚本添加执行权限并运行: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
相关产品推荐
相关产品推荐

