Browse Source

feat(dashboard): Enhance Vite plugin configuration for build output management

David Höck 7 months ago
parent
commit
257bc03267
1 changed files with 30 additions and 2 deletions
  1. 30 2
      packages/dashboard/vite/vite-plugin-config.ts

+ 30 - 2
packages/dashboard/vite/vite-plugin-config.ts

@@ -1,11 +1,39 @@
 import path from 'path';
-import { Plugin, UserConfig } from 'vite';
+import { ConfigEnv, Plugin, UserConfig } from 'vite';
 
 export function viteConfigPlugin({ packageRoot }: { packageRoot: string }): Plugin {
     return {
         name: 'vendure:vite-config-plugin',
-        config: (config: UserConfig) => {
+        config: (config: UserConfig, env: ConfigEnv) => {
+            // Only set the vite `root` to the dashboard package when running the dev server.
+            // During a production build we still need to reference the dashboard source which
+            // lives in `node_modules`, but we don't want the build output to be emitted in there.
+            // Therefore we set `root` only for `serve` and, for `build`, we instead make sure that
+            // an `outDir` **outside** of `node_modules` is used (defaulting to the current working
+            // directory if the user did not provide one already).
             config.root = packageRoot;
+
+            // If we are building and no explicit outDir has been provided (or it is a relative path),
+            // set it to an **absolute** path relative to the cwd so that the output never ends up in
+            // `node_modules`.
+            if (env.command === 'build') {
+                const buildConfig = config.build ?? {};
+
+                const hasOutDir = typeof buildConfig.outDir === 'string' && buildConfig.outDir.length > 0;
+                const outDirIsAbsolute = hasOutDir && path.isAbsolute(buildConfig.outDir as string);
+
+                const normalizedOutDir = hasOutDir
+                    ? outDirIsAbsolute
+                        ? (buildConfig.outDir as string)
+                        : path.resolve(process.cwd(), buildConfig.outDir as string)
+                    : path.resolve(process.cwd(), 'dist/vendure-dashboard');
+
+                config.build = {
+                    ...buildConfig,
+                    outDir: normalizedOutDir,
+                };
+            }
+
             config.resolve = {
                 alias: {
                     ...(config.resolve?.alias ?? {}),