html.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. export function configHtmlPlugin(env: ViteEnv, isBuild: boolean) {
  10. const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env;
  11. const path = VITE_PUBLIC_PATH.endsWith('/') ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/`;
  12. const getAppConfigSrc = () => {
  13. return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`;
  14. };
  15. const htmlPlugin: PluginOption[] = createHtmlPlugin({
  16. minify: isBuild,
  17. inject: {
  18. // 修改模板html的标题
  19. data: {
  20. title: VITE_GLOB_APP_TITLE,
  21. },
  22. // 将app.config.js文件注入到模板html中
  23. tags: isBuild
  24. ? [
  25. {
  26. tag: 'script',
  27. attrs: {
  28. src: getAppConfigSrc(),
  29. },
  30. },
  31. ]
  32. : [],
  33. },
  34. });
  35. return htmlPlugin;
  36. }