copy-version-to-standalone.cjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const fs = require("node:fs");
  2. const path = require("node:path");
  3. function copyDirIfExists(srcDir, dstDir) {
  4. if (!fs.existsSync(srcDir)) {
  5. console.warn(`[copy-standalone] Skip missing dir: ${srcDir}`);
  6. return;
  7. }
  8. fs.mkdirSync(path.dirname(dstDir), { recursive: true });
  9. fs.cpSync(srcDir, dstDir, { recursive: true, force: true });
  10. console.log(`[copy-standalone] Copied ${srcDir} -> ${dstDir}`);
  11. }
  12. function extractStandaloneNextConfig(serverJsPath) {
  13. if (!fs.existsSync(serverJsPath)) {
  14. throw new Error(`[copy-standalone] Generated server not found: ${serverJsPath}`);
  15. }
  16. const content = fs.readFileSync(serverJsPath, "utf8");
  17. const match = content.match(/const nextConfig = (.+?)\n\nprocess\.env\.__NEXT_PRIVATE_STANDALONE_CONFIG/s);
  18. if (!match) {
  19. throw new Error("[copy-standalone] Failed to extract standalone nextConfig");
  20. }
  21. return JSON.parse(match[1]);
  22. }
  23. const src = path.resolve(process.cwd(), "VERSION");
  24. const dstDir = path.resolve(process.cwd(), ".next", "standalone");
  25. const dst = path.join(dstDir, "VERSION");
  26. if (!fs.existsSync(src)) {
  27. console.error(`[copy-version] VERSION not found at ${src}`);
  28. process.exit(1);
  29. }
  30. fs.mkdirSync(dstDir, { recursive: true });
  31. fs.copyFileSync(src, dst);
  32. console.log(`[copy-version] Copied VERSION -> ${dst}`);
  33. const standaloneServerPath = path.join(dstDir, "server.js");
  34. const nextConfig = extractStandaloneNextConfig(standaloneServerPath);
  35. fs.writeFileSync(
  36. path.join(dstDir, "standalone-next-config.json"),
  37. JSON.stringify(nextConfig)
  38. );
  39. fs.copyFileSync(path.resolve(process.cwd(), "server.js"), standaloneServerPath);
  40. console.log(`[copy-standalone] Replaced standalone server -> ${standaloneServerPath}`);
  41. // Make standalone output self-contained for local `node .next/standalone/server.js` runs.
  42. // Next.js standalone requires `.next/static` and `public` to exist next to `server.js`.
  43. copyDirIfExists(
  44. path.resolve(process.cwd(), ".next", "static"),
  45. path.resolve(dstDir, ".next", "static")
  46. );
  47. copyDirIfExists(path.resolve(process.cwd(), "public"), path.resolve(dstDir, "public"));