1616
1717import { defineConfig } from 'vite' ;
1818import dotenv from 'dotenv' ;
19+ import { resolve , basename } from 'path' ;
1920
2021dotenv . config ( ) ;
2122
22- export default defineConfig ( {
23- root : '../' ,
23+ export default defineConfig ( ( { command } ) => {
24+ // __dirname is /Users/wfrench/git/js-api-samples/samples/
25+ const projectRepoRoot = resolve ( __dirname , '..' ) ; // /Users/wfrench/git/js-api-samples/
26+
27+ let effectiveOutDir ;
28+ let effectiveBuildInput = { } ; // For rollupOptions.input
29+
30+ if ( command === 'build' ) {
31+ // When `npm run build:vite --workspace=.` is run from a sample's directory,
32+ // process.cwd() will be the path to that sample's directory.
33+ const workspaceDir = process . cwd ( ) ; // e.g., /Users/wfrench/git/js-api-samples/samples/test-example
34+ const samplesBaseDir = resolve ( projectRepoRoot , 'samples' ) ;
35+
36+ // Ensure we are building a specific sample within the 'samples' directory
37+ if ( workspaceDir . startsWith ( samplesBaseDir ) && workspaceDir !== samplesBaseDir ) {
38+ const workspaceName = basename ( workspaceDir ) ; // e.g., "test-example"
39+ // Output to project_root/dist/samples/workspace_name/dist/
40+ // This path must be relative to Vite's `root` option.
41+ effectiveOutDir = resolve ( projectRepoRoot , 'dist' , 'samples' , workspaceName , 'dist' ) ;
42+ // Vite's `root` is projectRepoRoot, so input path is relative to that.
43+ effectiveBuildInput [ resolve ( workspaceDir , 'index.html' ) ] = resolve ( workspaceDir , 'index.html' ) ;
44+ } else {
45+ // Fallback for builds not initiated from a specific workspace.
46+ // This shouldn't happen with your current per-sample build scripts.
47+ console . warn ( `Vite build initiated from unexpected directory: ${ workspaceDir } . Defaulting output to root of dist.` ) ;
48+ effectiveOutDir = resolve ( projectRepoRoot , 'dist' ) ;
49+ }
50+ }
51+
52+ return {
53+ root : projectRepoRoot , // Vite's project root is js-api-samples/
2454 build : {
25- emptyOutDir : true ,
26- outDir : '../dist' ,
55+ emptyOutDir : false , // Crucial: Do not empty the main dist dir for each sample.
56+ outDir : effectiveOutDir || resolve ( projectRepoRoot , 'dist' ) , // Default for serve/preview
57+ rollupOptions : command === 'build' && Object . keys ( effectiveBuildInput ) . length > 0 ? { input : effectiveBuildInput } : undefined ,
2758 } ,
2859 preview : {
2960 port : 8080 ,
@@ -32,4 +63,5 @@ export default defineConfig({
3263 define : {
3364 'import.meta.env.GOOGLE_MAPS_API_KEY' : JSON . stringify ( process . env . GOOGLE_MAPS_API_KEY )
3465 }
66+ } ;
3567} ) ;
0 commit comments