html.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. const git = simpleGit();
  11. async function getLatestHash() {
  12. const gitLog = await git.log();
  13. /** 截取git hash值最后8位 */
  14. const lastStrNum = 8;
  15. return gitLog.latest?.hash.substring(-lastStrNum, lastStrNum);
  16. }
  17. export function configHtmlPlugin(env: ViteEnv, isBuild: boolean): Promise<PluginOption[]> {
  18. const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env;
  19. const path = VITE_PUBLIC_PATH.endsWith('/') ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/`;
  20. const getAppConfigSrc = () => {
  21. return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`;
  22. };
  23. return new Promise((resolve) => {
  24. getLatestHash().then((hash) => {
  25. const htmlPlugin: PluginOption[] = createHtmlPlugin({
  26. minify: isBuild,
  27. inject: {
  28. // Inject data into ejs template
  29. data: {
  30. title: VITE_GLOB_APP_TITLE,
  31. hash,
  32. },
  33. // Embed the generated app.config.js file
  34. tags: isBuild
  35. ? [
  36. {
  37. tag: 'script',
  38. attrs: {
  39. src: getAppConfigSrc(),
  40. },
  41. },
  42. ]
  43. : [],
  44. },
  45. });
  46. resolve(htmlPlugin);
  47. });
  48. });
  49. }