Procházet zdrojové kódy

fix(dashboard): Fix handling of Vite base option

Michael Bromley před 7 měsíci
rodič
revize
f21a0b646f

+ 38 - 0
packages/dashboard/vite/vite-plugin-transform-index.ts

@@ -0,0 +1,38 @@
+import { Plugin, ResolvedConfig } from 'vite';
+
+/**
+ * @description
+ * This Vite plugin handles the scenario where the `base` path is set in the Vite config.
+ * The default Vite behavior is to prepend the `base` path to all `href` and `src` attributes in the HTML,
+ * but this causes the Vendure Dashboard not to load its assets correctly.
+ *
+ * This plugin removes the `base` path from all `href` and `src` attributes in the HTML,
+ * and adds a `<base>` tag to the `<head>` of the HTML document.
+ */
+export function transformIndexHtmlPlugin(): Plugin {
+    let config: ResolvedConfig;
+    return {
+        name: 'vendure:vite-config-transform-index-html',
+        configResolved(resolvedConfig) {
+            // store the resolved config
+            config = resolvedConfig;
+        },
+        transformIndexHtml(html) {
+            if (config.base && config.base !== '/') {
+                // Remove the base path from hrefs and srcs
+                const basePath = config.base.replace(/\/$/, ''); // Remove trailing slash
+
+                // Single regex to handle both href and src attributes with any quote type
+                const attributeRegex = new RegExp(`(href|src)=(["'])${basePath}`, 'g');
+                let transformedHtml = html.replace(attributeRegex, '$1=$2');
+
+                // Add base tag to head
+                const baseTag = `        <base href="${config.base}">\n`;
+                transformedHtml = transformedHtml.replace(/<head>/, `<head>\n${baseTag}`);
+
+                return transformedHtml;
+            }
+            return html;
+        },
+    };
+}

+ 2 - 0
packages/dashboard/vite/vite-plugin-vendure-dashboard.ts

@@ -10,6 +10,7 @@ import { viteConfigPlugin } from './vite-plugin-config.js';
 import { dashboardMetadataPlugin } from './vite-plugin-dashboard-metadata.js';
 import { gqlTadaPlugin } from './vite-plugin-gql-tada.js';
 import { ThemeVariablesPluginOptions, themeVariablesPlugin } from './vite-plugin-theme.js';
+import { transformIndexHtmlPlugin } from './vite-plugin-transform-index.js';
 import { UiConfigPluginOptions, uiConfigPlugin } from './vite-plugin-ui-config.js';
 
 /**
@@ -92,6 +93,7 @@ export function vendureDashboardPlugin(options: VitePluginVendureDashboardOption
         ...(options.gqlTadaOutputPath
             ? [gqlTadaPlugin({ gqlTadaOutputPath: options.gqlTadaOutputPath, tempDir, packageRoot })]
             : []),
+        transformIndexHtmlPlugin(),
     ];
 }