html.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 { Plugin } from 'vite';
  6. import html 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_GLOB_PUBLIC_PATH, VITE_GLOB_CONTENT_SECURITY_POLICY } = env;
  11. const path = VITE_GLOB_PUBLIC_PATH.endsWith('/')
  12. ? VITE_GLOB_PUBLIC_PATH
  13. : `${VITE_GLOB_PUBLIC_PATH}/`;
  14. const getAppConfigSrc = () => {
  15. return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`;
  16. };
  17. const htmlPlugin: Plugin[] = html({
  18. minify: isBuild,
  19. inject: {
  20. // Inject data into ejs template
  21. injectData: {
  22. title: VITE_GLOB_APP_TITLE,
  23. contentSecurityPolicy: VITE_GLOB_CONTENT_SECURITY_POLICY
  24. ? `<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />`
  25. : '',
  26. },
  27. // Embed the generated app.config.js file
  28. tags: isBuild
  29. ? [
  30. {
  31. tag: 'script',
  32. attrs: {
  33. src: getAppConfigSrc(),
  34. },
  35. },
  36. ]
  37. : [],
  38. },
  39. });
  40. return htmlPlugin;
  41. }