node:19.4.0
next:14.2.5
// next.config.js
const nextConfig = {
      output: "standalone",
      ...
};
  1. next build之后会生成一个.next文件夹
  2. 在根目录下创建编写server.js文件
const path = require("path");
const address = require("address");
const copyDir = require("copy-dir");

// 拷贝外层public文件夹到standalone文件夹下
copyDir.sync(path.join(__dirname, "public"), path.join(__dirname, ".next/standalone/public"), { cover: true });

// 拷贝static到standalone/.next文件夹下
copyDir.sync(path.join(__dirname, ".next/static"), path.join(__dirname, ".next/standalone/.next/static"), { cover: true });

// 设置IP
const HOSTNAME = address.ip();
process.env.HOSTNAME = HOSTNAME;

// 启动打包后的next项目
require("./.next/standalone/server.js");
  1. package.json添加启动命令
  "scripts": {
    "dev": "cross-env next dev",
    "build": "cross-env next build",
    "start": "next start",
    "start:3343": "next start -p 3343", 
    "server:standalone": "node ./.next/standalone/server.js",
    "server:standalone:3343": "cross-env PORT=3343 node ./.next/standalone/server.js",
    // 添加的命令
    "server": "cross-env PORT=3343 node ./server.js"
  },
  1. 启动
    npm run server
> xxxxxxx@0.1.0 server
> cross-env PORT=3343 node ./server.js

  ▲ Next.js 14.2.5
  - Local:        http://xxx.xxx.x.xxx:3343
  - Network:      http://xxx.xxx.x.xxx:3343

 ✓ Starting...
 ✓ Ready in 120ms
  1. Dockerfile

perkz
51 声望28 粉丝

« 上一篇
工具