post-build.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // post-build.js
  2. 'use strict';
  3. const fs = require('fs');
  4. // import fs from 'node:fs'
  5. const CDN_URL = process.env.CDN_URL || '';
  6. /**
  7. * CDN 地址,build 时用到。
  8. * 如无需使用CDN(比如H5平台有时会不适用CDN),则打包时使用类似 CDN_URL= yarn build:h5 的命令
  9. * */
  10. const publicPath =
  11. CDN_URL !== undefined
  12. ? CDN_URL
  13. : VUE_APP_STAGE === 'prod'
  14. ? 'https://static.kerryprops.com.cn/kip/temporary-parking-frontend'
  15. : 'https://static-le.kerryprops.com.cn/kip/temporary-parking-frontend';
  16. /**
  17. * 返回当前git repo的header的commit id
  18. * @returns commit id,例如 fe40cff4c4a9b55eaf215ac79a0c37c079b067cd
  19. * @see https://stackoverflow.com/a/56975550/196519
  20. */
  21. function gitHash() {
  22. try {
  23. const rev = fs
  24. .readFileSync('.git/HEAD')
  25. .toString()
  26. .trim()
  27. .split(/.*[: ]/)
  28. .slice(-1)[0];
  29. if (rev.indexOf('/') === -1) {
  30. return rev;
  31. } else {
  32. return fs
  33. .readFileSync('.git/' + rev)
  34. .toString()
  35. .trim();
  36. }
  37. } catch (e) {
  38. // eslint-disable-next-line no-console
  39. console.log(e);
  40. return 'git_hash_error';
  41. }
  42. }
  43. /**
  44. * 更新 build:h5 生成的 html
  45. * 1. 写入 build 信息
  46. * 2. 更新 uni.css 的地址为 CDN 地址
  47. */
  48. const updateIndexHtml = () => {
  49. const htmlPath = 'dist/index.html';
  50. let html = fs.readFileSync(htmlPath).toString();
  51. // 写入 build 信息
  52. html += '\r\n<!-- ';
  53. html = html + '\r\n build time:' + new Date().toUTCString() + '; ';
  54. html = html + '\r\n BUILD_NUMBER:' + process.env.BUILD_NUMBER + '; ';
  55. html = html + '\r\n GIT_COMMIT:' + gitHash() + '; ';
  56. html += '\r\n -->';
  57. // uni-app 会把 uni.css 注入到 index.html 中,但是是放在 /static/ 下面,需要替换为 CDN 地址
  58. html = html.replace(/"(\/static\/uni\..+\.css)"/gm, `"${publicPath}$1"`);
  59. fs.writeFileSync(htmlPath, html);
  60. console.log(`insert timestamp and env into index.html.`);
  61. };
  62. const postBuild = () => {
  63. updateIndexHtml();
  64. }
  65. try {
  66. postBuild();
  67. } catch (err) {
  68. console.log(77, err);
  69. }