// post-build.js 'use strict'; const fs = require('fs'); // import fs from 'node:fs' const CDN_URL = process.env.CDN_URL || ''; /** * CDN 地址,build 时用到。 * 如无需使用CDN(比如H5平台有时会不适用CDN),则打包时使用类似 CDN_URL= yarn build:h5 的命令 * */ const publicPath = CDN_URL !== undefined ? CDN_URL : VUE_APP_STAGE === 'prod' ? 'https://static.kerryprops.com.cn/kip/temporary-parking-frontend' : 'https://static-le.kerryprops.com.cn/kip/temporary-parking-frontend'; /** * 返回当前git repo的header的commit id * @returns commit id,例如 fe40cff4c4a9b55eaf215ac79a0c37c079b067cd * @see https://stackoverflow.com/a/56975550/196519 */ function gitHash() { try { const rev = fs .readFileSync('.git/HEAD') .toString() .trim() .split(/.*[: ]/) .slice(-1)[0]; if (rev.indexOf('/') === -1) { return rev; } else { return fs .readFileSync('.git/' + rev) .toString() .trim(); } } catch (e) { // eslint-disable-next-line no-console console.log(e); return 'git_hash_error'; } } /** * 更新 build:h5 生成的 html * 1. 写入 build 信息 * 2. 更新 uni.css 的地址为 CDN 地址 */ const updateIndexHtml = () => { const htmlPath = 'dist/index.html'; let html = fs.readFileSync(htmlPath).toString(); // 写入 build 信息 html += '\r\n'; // uni-app 会把 uni.css 注入到 index.html 中,但是是放在 /static/ 下面,需要替换为 CDN 地址 html = html.replace(/"(\/static\/uni\..+\.css)"/gm, `"${publicPath}$1"`); fs.writeFileSync(htmlPath, html); console.log(`insert timestamp and env into index.html.`); }; const postBuild = () => { updateIndexHtml(); } try { postBuild(); } catch (err) { console.log(77, err); }