html.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Plugin to minimize and use ejs template syntax in index.html.
  3. * https://github.com/anncwb/vite-plugin-html
  4. */
  5. import type { PluginOption } from 'vite';
  6. import { createHtmlPlugin } from 'vite-plugin-html';
  7. // import pkg from '../../../package.json';
  8. // import { GLOB_CONFIG_FILE_NAME } from '../../constant';
  9. import { simpleGit } from 'simple-git';
  10. import dayjs from 'dayjs';
  11. const git = simpleGit();
  12. async function getLatestHash() {
  13. const gitLog = await git.log();
  14. /** 截取git hash值最后8位 */
  15. const lastStrNum = 8;
  16. return gitLog.latest?.hash.substring(-lastStrNum, lastStrNum);
  17. }
  18. async function getBuildInfo() {
  19. const { current } = await git.branchLocal();
  20. const hash = await getLatestHash();
  21. return { currentBranch: current, hash };
  22. }
  23. export function configHtmlPlugin(env: ViteEnv, isBuild: boolean): Promise<PluginOption[]> {
  24. const { VITE_GLOB_APP_TITLE } = env;
  25. return new Promise((resolve) => {
  26. getBuildInfo().then(({ currentBranch, hash }) => {
  27. const htmlPlugin: PluginOption[] = createHtmlPlugin({
  28. minify: isBuild,
  29. inject: {
  30. // Inject data into ejs template
  31. data: {
  32. title: VITE_GLOB_APP_TITLE,
  33. hash,
  34. injectScript: `
  35. <script type="text/javascript">
  36. console.log("%cbuild branch, ${currentBranch}","background:#1777FF; padding: 3px 6px; border-radius: 4px" )
  37. console.log("%cbuild version: ${hash}", "background:#1777FF; padding: 3px 6px; border-radius: 4px");
  38. console.log("build time, ${dayjs().format('YYYY-MM-DD HH:mm:ss')}", )
  39. </script>`,
  40. },
  41. // // Embed the generated app.config.js file
  42. // tags: isBuild
  43. // ? [
  44. // {
  45. // tag: 'script',
  46. // attrs: {
  47. // src: getAppConfigSrc(),
  48. // },
  49. // },
  50. // ]
  51. // : [],
  52. },
  53. });
  54. resolve(htmlPlugin);
  55. });
  56. });
  57. }