|
|
@@ -0,0 +1,44 @@
|
|
|
+#!/usr/bin/env node
|
|
|
+/**
|
|
|
+ * 用指定 env 文件注入 process.env 后执行 next build。
|
|
|
+ * 已注入的变量优先于 .env.production(Next 不会覆盖已有 process.env)。
|
|
|
+ */
|
|
|
+import { readFileSync, existsSync } from "fs";
|
|
|
+import { spawnSync } from "child_process";
|
|
|
+import { resolve, dirname } from "path";
|
|
|
+import { fileURLToPath } from "url";
|
|
|
+
|
|
|
+const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
|
+const root = resolve(__dirname, "..");
|
|
|
+const envFile = process.argv[2] || ".env.development";
|
|
|
+const envPath = resolve(root, envFile);
|
|
|
+
|
|
|
+if (!existsSync(envPath)) {
|
|
|
+ console.error(`[build-with-env] 找不到 ${envPath}`);
|
|
|
+ process.exit(1);
|
|
|
+}
|
|
|
+
|
|
|
+const env = { ...process.env, NODE_ENV: "production" };
|
|
|
+
|
|
|
+for (const line of readFileSync(envPath, "utf8").split("\n")) {
|
|
|
+ const trimmed = line.trim();
|
|
|
+ if (!trimmed || trimmed.startsWith("#")) continue;
|
|
|
+ const eq = trimmed.indexOf("=");
|
|
|
+ if (eq === -1) continue;
|
|
|
+ const key = trimmed.slice(0, eq).trim();
|
|
|
+ let val = trimmed.slice(eq + 1).trim();
|
|
|
+ if (
|
|
|
+ (val.startsWith('"') && val.endsWith('"')) ||
|
|
|
+ (val.startsWith("'") && val.endsWith("'"))
|
|
|
+ ) {
|
|
|
+ val = val.slice(1, -1);
|
|
|
+ }
|
|
|
+ env[key] = val;
|
|
|
+}
|
|
|
+
|
|
|
+console.log(
|
|
|
+ `[build-with-env] ${envFile} → NEXT_PUBLIC_APP_ENV=${env.NEXT_PUBLIC_APP_ENV}, API_PROXY_TARGET=${env.API_PROXY_TARGET}`,
|
|
|
+);
|
|
|
+
|
|
|
+const r = spawnSync("next", ["build"], { cwd: root, env, stdio: "inherit" });
|
|
|
+process.exit(r.status ?? 1);
|