post-build.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // post-build.js
  2. 'use strict';
  3. const fs = require('fs');
  4. /**
  5. * 获取当前所在的 git commit 的 commit id
  6. * @returns {string} 执行成功时返回 commit id;否则返回 git_hash_error
  7. * https://stackoverflow.com/a/56975550/196519
  8. */
  9. const git_hash = () => {
  10. try {
  11. const rev = fs.readFileSync('.git/HEAD').toString().trim().split(/.*[: ]/).slice(-1)[0];
  12. if (rev.indexOf('/') === -1) {
  13. return rev;
  14. } else {
  15. return fs.readFileSync('.git/' + rev).toString().trim();
  16. }
  17. } catch (e) {
  18. // eslint-disable-next-line no-console
  19. console.log(e);
  20. return 'git_hash_error';
  21. }
  22. }
  23. /**
  24. * 插入 build info 到 index.html 中
  25. */
  26. const updateIndexHtml = () => {
  27. const htmlPath = 'dist/index.html';
  28. let html = fs.readFileSync(htmlPath).toString();
  29. html += '\r\n<!-- ';
  30. html = html + '\r\n build time:' + new Date().toUTCString() + '; ';
  31. // process.env.BUILD_NUMBER 是 Jenkins 执行 job 时传入的 env
  32. html = html + '\r\n BUILD_NUMBER:' + process.env.BUILD_NUMBER + '; ';
  33. html = html + '\r\n GIT_COMMIT:' + git_hash() + '; ';
  34. html += '\r\n -->';
  35. fs.writeFileSync(htmlPath, html);
  36. // eslint-disable-next-line no-console
  37. console.log(`Insert timestamp and env into index.html. -- DONE`);
  38. }
  39. const postBuild = () => {
  40. updateIndexHtml();
  41. }
  42. postBuild();