| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #!/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 nextCli = resolve(root, "node_modules/next/dist/bin/next");
- if (!existsSync(nextCli)) {
- console.error("[build-with-env] 未找到 next,请先在项目目录执行 npm install");
- process.exit(1);
- }
- const r = spawnSync(process.execPath, [nextCli, "build"], {
- cwd: root,
- env,
- stdio: "inherit",
- });
- if (r.error) {
- console.error("[build-with-env] 启动 next build 失败:", r.error.message);
- process.exit(1);
- }
- process.exit(r.status ?? 1);
|