buildTag.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * 在外部配置文件追加用于追踪版本的信息
  3. */
  4. import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
  5. import fs, { appendFileSync } from 'fs-extra';
  6. import { execSync } from 'node:child_process';
  7. import colors from 'picocolors';
  8. import { getRootPath } from '../utils';
  9. import pkg from '../../package.json';
  10. import dayjs from 'dayjs';
  11. interface CreateTagParams {
  12. configFileName?: string;
  13. }
  14. function createTag(params: CreateTagParams) {
  15. const { configFileName } = params;
  16. try {
  17. const prop = '__LAST_PRODUCTION_TAG__';
  18. const path = `window.${prop}`;
  19. const tag = {
  20. // last commit's SHA
  21. commit: execSync('git rev-parse --short HEAD').toString().replace('\n', ''),
  22. buildtime: dayjs().format('YYYY-MM-DD_HH:mm:ss'),
  23. };
  24. // Ensure that the variable will not be modified
  25. const evalExp = `
  26. ${path}=${JSON.stringify(tag)};
  27. Object.freeze(${path});
  28. Object.defineProperty(window, "${prop}", {
  29. configurable: false,
  30. writable: false,
  31. });`.replace(/\s/g, '');
  32. fs.mkdirp(getRootPath(OUTPUT_DIR));
  33. appendFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), evalExp);
  34. console.log(colors.cyan(`✨ [${pkg.name}]`) + ` - tag infomation generate successfully:`);
  35. console.log(colors.gray(OUTPUT_DIR + '/' + colors.green(configFileName)) + '\n');
  36. } catch (error) {
  37. console.log(colors.red('tag infomation generation failed to package:\n' + error));
  38. }
  39. }
  40. export function runBuildTag() {
  41. createTag({
  42. configFileName: GLOB_CONFIG_FILE_NAME,
  43. });
  44. }