This commit is contained in:
乘风
2026-02-05 11:35:57 +08:00
parent 8c2a6391af
commit b96acadf91
31 changed files with 2263 additions and 4933 deletions

View File

@@ -55,34 +55,52 @@ if (!fs.existsSync(standaloneDir)) {
process.exit(1);
}
// 复制静态资源
// 复制静态资源(缺一不可,否则部署到线上也会 404
console.log('📦 复制静态资源...');
if (!fs.existsSync(staticSrc)) {
console.error('❌ 错误:.next/static 不存在,请先执行 pnpm build');
process.exit(1);
}
console.log(' .next/static → .next/standalone/.next/static');
copyDir(staticSrc, staticDst);
const chunksDir = path.join(staticDst, 'chunks');
if (!fs.existsSync(chunksDir)) {
console.error('❌ 错误:复制后 .next/standalone/.next/static/chunks 不存在,本地会 404部署线上也会报错');
process.exit(1);
}
console.log(' public → .next/standalone/public');
copyDir(publicSrc, publicDst);
console.log('✅ 静态资源复制完成\n');
// 启动服务器
const serverPath = path.join(standaloneDir, 'server.js');
// 优先使用环境变量 PORT未设置时提示并退出
const port = process.env.PORT;
if (!port) {
console.error('❌ 错误:未设置 PORT 环境变量');
console.error(' 请设置端口后启动,例如:');
console.error(' PORT=30006 pnpm start');
console.error(' 或:');
console.error(' export PORT=30006 && pnpm start');
process.exit(1);
// 同步构建索引BUILD_ID、build-manifest 等,避免服务器用错版本导致 404
const nextRoot = path.join(rootDir, '.next');
const nextStandalone = path.join(standaloneDir, '.next');
const indexFiles = ['BUILD_ID', 'build-manifest.json', 'app-path-routes-manifest.json', 'routes-manifest.json'];
for (const name of indexFiles) {
const src = path.join(nextRoot, name);
const dst = path.join(nextStandalone, name);
if (fs.existsSync(src)) {
try {
fs.copyFileSync(src, dst);
} catch (e) {
console.warn(' [警告] 复制索引失败 %s: %s', name, e.message);
}
}
}
console.log(`🌐 启动服务器: http://localhost:${port}`);
console.log('');
console.log('✅ 静态资源与构建索引已同步\n');
const server = spawn('node', [serverPath], {
// 启动服务器(必须在 standalone 目录下运行,否则 _next/static 会 404
const serverPath = path.join(standaloneDir, 'server.js');
const DEFAULT_PORT = 30006;
const port = process.env.PORT || String(DEFAULT_PORT);
console.log(`🌐 启动服务器: http://localhost:${port}`);
console.log(' (静态资源已复制到 .next/standalone请勿直接 cd 到 standalone 用 node server.js)\n');
const server = spawn('node', ['server.js'], {
cwd: standaloneDir, // 关键:工作目录必须是 standalone否则找不到 .next/static
stdio: 'inherit',
env: { ...process.env, PORT: port }
});