chore: Load Vite and Vitest configs as ESM (#14101)

* chore: Load Vite and Vitest configs as ESM

* fix: Resolve _FILE variables in the Vite config environment

* fix: Do not log the secret file path in the Vite config

* fix: Silence the dotenvx injection log
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-16 01:40:47 +00:00
1 parent 0b37f70d2f
commit 2a4693687b
7 files changed
+98 -41

No files matched your search

@@ -147,7 +147,7 @@ EOF
(cd "$SRC" && node build.js) >"$RUN_DIR/build-server.log" 2>&1 ||
die "server build failed, see $RUN_DIR/build-server.log"
log "building frontend (vite)"
(cd "$SRC" && NODE_ENV=production VITE_CJS_IGNORE_WARNING=true node_modules/.bin/vite build) \
(cd "$SRC" && NODE_ENV=production node_modules/.bin/vite build) \
>"$RUN_DIR/build-app.log" 2>&1 || die "frontend build failed, see $RUN_DIR/build-app.log"
log "migrating database"
+2 -2
View File
@@ -42,8 +42,8 @@ jobs:
- '!shared/i18n/locales/**'
config:
- '.github/**'
- 'vite.config.ts'
- 'vitest.config.ts'
- 'vite.config.mts'
- 'vitest.config.mts'
server:
- 'server/**'
- 'shared/**'
+1
View File
@@ -1,5 +1,6 @@
require("@dotenvx/dotenvx").config({
path: process.env.NODE_ENV === "test" ? ".env.test" : ".env",
quiet: true,
});
var path = require('path');
+3 -3
View File
@@ -33,9 +33,9 @@
"test:shared": "TZ=UTC vitest run --project shared-node --project shared-jsdom",
"test:server": "TZ=UTC vitest run --project \"server*\"",
"test:watch": "TZ=UTC vitest",
"vite:dev": "VITE_CJS_IGNORE_WARNING=true vite",
"vite:build": "VITE_CJS_IGNORE_WARNING=true vite build",
"vite:preview": "VITE_CJS_IGNORE_WARNING=true vite preview"
"vite:dev": "vite",
"vite:build": "vite build",
"vite:preview": "vite preview"
},
"funding": {
"type": "GitHub Sponsors ❤",
+1 -1
View File
@@ -1,7 +1,7 @@
if (process.env.NODE_ENV !== "test") {
// oxlint-disable-next-line @typescript-eslint/no-var-requires
require("@dotenvx/dotenvx").config({
silent: true,
quiet: true,
ignore: ["MISSING_ENV_FILE"],
});
}
+83 -27
View File
@@ -1,39 +1,42 @@
import fs from "node:fs";
import path from "node:path";
import dotenv from "@dotenvx/dotenvx";
import react from "@vitejs/plugin-react";
import browserslistToEsbuild from "browserslist-to-esbuild";
import webpackStats from "rollup-plugin-webpack-stats";
import type { ConfigEnv, ServerOptions } from "vite";
import { defineConfig } from "vite";
import { VitePWA } from "vite-plugin-pwa";
import environment from "./server/utils/environment";
let httpsConfig: ServerOptions["https"] | undefined;
let host: string | undefined;
export default ({ mode }: ConfigEnv) => {
const env = loadEnvironment();
// The Vite dev server listens on the port after the app server.
const port = (parseInt(environment.PORT ?? "", 10) || 3000) + 1;
let httpsConfig: ServerOptions["https"] | undefined;
let host: string | undefined;
if (environment.NODE_ENV === "development") {
host = host = new URL(environment.URL!).hostname;
// The Vite dev server listens on the port after the app server.
const port = (parseInt(env("PORT") ?? "", 10) || 3000) + 1;
try {
httpsConfig = {
key: fs.readFileSync("./server/config/certs/private.key"),
cert: fs.readFileSync("./server/config/certs/public.cert"),
};
} catch (_err) {
// oxlint-disable-next-line no-console
console.warn("No local SSL certs found, HTTPS will not be available");
if (env("NODE_ENV") === "development") {
const url = env("URL");
host = url ? new URL(url).hostname : undefined;
try {
httpsConfig = {
key: fs.readFileSync("./server/config/certs/private.key"),
cert: fs.readFileSync("./server/config/certs/public.cert"),
};
} catch {
// oxlint-disable-next-line no-console
console.warn("No local SSL certs found, HTTPS will not be available");
}
}
}
export default ({ mode }: ConfigEnv) =>
defineConfig({
// The local .env file can set NODE_ENV=development in process.env via the
// environment import above, which would cause Vite to bundle development
// builds of dependencies such as React. Derive the bundled value from the
// Vite mode instead so `vite build` always bundles production dependencies.
return defineConfig({
// The local .env file can set NODE_ENV=development, which would cause Vite
// to bundle development builds of dependencies such as React. Derive the
// bundled value from the Vite mode instead so `vite build` always bundles
// production dependencies.
define: {
"process.env.NODE_ENV": JSON.stringify(
mode === "development" ? "development" : "production"
@@ -41,7 +44,7 @@ export default ({ mode }: ConfigEnv) =>
},
root: "./",
publicDir: "./server/static",
base: (environment.CDN_URL ?? "") + "/static/",
base: (env("CDN_URL") ?? "") + "/static/",
server: {
port,
strictPort: true,
@@ -50,7 +53,7 @@ export default ({ mode }: ConfigEnv) =>
allowedHosts: host ? [host] : undefined,
cors: true,
fs:
environment.NODE_ENV === "development"
env("NODE_ENV") === "development"
? {
// Allow serving files from one level up to the project root
allow: [".."],
@@ -68,7 +71,7 @@ export default ({ mode }: ConfigEnv) =>
globPatterns: ["**/*.{css,ico,png,svg}"],
navigateFallback: null,
modifyURLPrefix: {
"": `${environment.CDN_URL ?? ""}/static/`,
"": `${env("CDN_URL") ?? ""}/static/`,
},
skipWaiting: true,
clientsClaim: true,
@@ -189,8 +192,8 @@ export default ({ mode }: ConfigEnv) =>
],
resolve: {
alias: {
"~": path.resolve(__dirname, "./app"),
"@shared": path.resolve(__dirname, "./shared"),
"~": path.resolve(import.meta.dirname, "./app"),
"@shared": path.resolve(import.meta.dirname, "./shared"),
},
},
build: {
@@ -282,3 +285,56 @@ export default ({ mode }: ConfigEnv) =>
},
},
});
};
/**
* Loads the .env files with the same precedence as server/utils/environment.ts.
* That file cannot be imported here, as Vite loads it as CommonJS.
*
* @returns a getter for a variable, where process.env takes precedence and an
* unset variable is read from the file named by its `_FILE` variable.
*/
function loadEnvironment(): (key: string) => string | undefined {
const read = (file: string) => {
const filePath = path.resolve(import.meta.dirname, file);
return fs.existsSync(filePath)
? dotenv.parse(fs.readFileSync(filePath, "utf8"))
: {};
};
const envDefault = read(".env");
const nodeEnvs = [process.env.NODE_ENV, envDefault.NODE_ENV];
const isDevelopment = nodeEnvs.includes("development");
// Load environment specific variables, in reverse order of precedence.
const environment = ["production", "development", "local", "test"]
.filter(
(env) => nodeEnvs.includes(env) || (env === "local" && isDevelopment)
)
.reduce<Record<string, string>>(
(acc, env) => ({ ...acc, ...read(`.env.${env}`) }),
{}
);
const merged: Record<string, string | undefined> = {
...envDefault,
...environment,
...process.env,
};
return (key) => {
const value = merged[key];
const filePath = merged[`${key}_FILE`];
if (value !== undefined || !filePath) {
return value;
}
try {
return fs.readFileSync(filePath, "utf8").trim();
} catch {
// oxlint-disable-next-line no-console
console.error(`Failed to read file for ${key}_FILE`);
return undefined;
}
};
}
+7 -7
View File
@@ -11,13 +11,13 @@ import { configDefaults, defineConfig } from "vitest/config";
delete process.env.SSL_CERT_FILE;
const aliases = {
"@server": path.resolve(__dirname, "./server"),
"@shared": path.resolve(__dirname, "./shared"),
"~": path.resolve(__dirname, "./app"),
plugins: path.resolve(__dirname, "./plugins"),
"@server": path.resolve(import.meta.dirname, "./server"),
"@shared": path.resolve(import.meta.dirname, "./shared"),
"~": path.resolve(import.meta.dirname, "./app"),
plugins: path.resolve(import.meta.dirname, "./plugins"),
};
const fileMock = path.resolve(__dirname, "./__mocks__/fileMock.js");
const fileMock = path.resolve(import.meta.dirname, "./__mocks__/fileMock.js");
// Mirrors the server build's SWC config (.swcrc). `decoratorMetadata` stays off
// because every @Column has an explicit DataType, and emitting it would throw
@@ -67,11 +67,11 @@ const serverTestFiles = [
const ISOLATED_MARKER = "@vitest-isolate true";
const isolatedServerTestFiles = globSync(serverTestFiles, {
cwd: __dirname,
cwd: import.meta.dirname,
posix: true,
}).filter((file) => {
const header = fs
.readFileSync(path.join(__dirname, file), "utf8")
.readFileSync(path.join(import.meta.dirname, file), "utf8")
.slice(0, 512);
return header.includes(ISOLATED_MARKER);
});