vite-plugin-transform-index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Plugin, ResolvedConfig } from 'vite';
  2. /**
  3. * @description
  4. * This Vite plugin handles the scenario where the `base` path is set in the Vite config.
  5. * The default Vite behavior is to prepend the `base` path to all `href` and `src` attributes in the HTML,
  6. * but this causes the Vendure Dashboard not to load its assets correctly.
  7. *
  8. * This plugin removes the `base` path from all `href` and `src` attributes in the HTML,
  9. * and adds a `<base>` tag to the `<head>` of the HTML document.
  10. */
  11. export function transformIndexHtmlPlugin(): Plugin {
  12. let config: ResolvedConfig;
  13. return {
  14. name: 'vendure:vite-config-transform-index-html',
  15. configResolved(resolvedConfig) {
  16. // store the resolved config
  17. config = resolvedConfig;
  18. },
  19. // Only apply this plugin during the build phase
  20. apply: 'build',
  21. transformIndexHtml(html) {
  22. if (config.base && config.base !== '/') {
  23. // Remove the base path from hrefs and srcs
  24. const basePath = config.base.replace(/\/$/, ''); // Remove trailing slash
  25. // Single regex to handle both href and src attributes with any quote type
  26. const attributeRegex = new RegExp(`(href|src)=(["'])${basePath}/?`, 'g');
  27. let transformedHtml = html.replace(attributeRegex, '$1=$2');
  28. // Add base tag to head
  29. const baseTag = ` <base href="${config.base}">\n`;
  30. transformedHtml = transformedHtml.replace(/<head>/, `<head>\n${baseTag}`);
  31. return transformedHtml;
  32. }
  33. return html;
  34. },
  35. };
  36. }