getBuildConfig defaulted to the whole import.meta.env, so Vite inlined every loaded VITE_* value, read or not. Values are now read by key, a lint rule bans whole-object references in src, and vite.config refuses VITE_* names missing from ENV_REGISTRY. A build test pins the values that must stay in the bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import { defineConfig, loadEnv } from "vite";
|
|
import react from "@vitejs/plugin-react";
|
|
import tailwindcss from "@tailwindcss/vite";
|
|
|
|
import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts";
|
|
import { ENV_REGISTRY } from "./src/contracts/env.ts";
|
|
|
|
/**
|
|
* 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once
|
|
* something bundles it, so a value the build does not declare is refused
|
|
* rather than carried along.
|
|
*/
|
|
function assertDeclaredBuildVariables(mode: string): void {
|
|
const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_"))
|
|
.filter((name) => !Object.hasOwn(ENV_REGISTRY, name))
|
|
.sort();
|
|
if (undeclared.length > 0) {
|
|
throw new Error(
|
|
`Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` +
|
|
"Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " +
|
|
"VITE_ values are published to the browser.",
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* §6.1. One sub-path, declared once.
|
|
*
|
|
* `VITE_ROUTER_BASE_PATH` already drives the router and the Service Worker
|
|
* scope. Vite's asset `base` was left at its default, so a build served from
|
|
* `/app/` emitted root-absolute asset URLs and loaded nothing: the three
|
|
* consumers of the same setting disagreed. They are read from one value here so
|
|
* a sub-path deployment is coherent or fails at build time.
|
|
*/
|
|
function routerBasePath(environment: NodeJS.ProcessEnv): string {
|
|
const declared = environment["VITE_ROUTER_BASE_PATH"];
|
|
if (declared === undefined || declared === "") return "/";
|
|
if (!declared.startsWith("/") || !declared.endsWith("/")) {
|
|
throw new Error(
|
|
`VITE_ROUTER_BASE_PATH must start and end with "/"; received ${declared}`,
|
|
);
|
|
}
|
|
return declared;
|
|
}
|
|
|
|
export default defineConfig(({ mode }) => {
|
|
assertDeclaredBuildVariables(mode);
|
|
return {
|
|
base: routerBasePath(process.env),
|
|
plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()],
|
|
build: {
|
|
manifest: true,
|
|
sourcemap: false,
|
|
},
|
|
};
|
|
});
|