如何在 next.js 中设置端口

How to Set port in next.js

一个应用程序运行正在端口 3000 上运行,我想 运行 另一个应用程序在默认端口的不同端口上运行。我如何在 React Next.js 中改变它。 我的 package.js 脚本是

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },

启动脚本命令是 npm run dev

这对我有用

 "scripts": { 
       "dev": "next -p 8080" 
},

只需要做:

yarn dev -p PORT_YOU_LIKE
"scripts": {
    "dev": "next dev -p 8080", // for dev 
    "start": "next start -p 8080" // for prod
},

有两种方法:

在您的 package.json 文件中,将 -p 8080 添加到 dev/start 脚本以在端口 8080 上启动服务器:

  "scripts": {
    "dev": "next -p 8080",
    "build": "next build",
    "profile-build": "next build --profile",
    "start": "next start -p 8080"
  }

或者,如果您不想在 package.json 文件中对此进行硬编码,您可以使用 ENV 变量 PORT 启动脚本。

PORT=8080 npm run dev

访问 vercel documentation 了解更多信息。

默认情况下,应用程序将从 http://localhost:3000 启动。可以使用 -p 更改默认端口,如下所示:

 npx next dev -p 4000

或者使用 PORT 环境变量:

PORT=4000 npx next dev

#注意我用的是 npx 而不是 npm

您还可以将主机名设置为不同于默认值 0.0.0.0,这对于使应用程序可用于网络上的其他设备很有用。可以使用 -H 更改默认主机名,如下所示:

 npx next dev -H 192.168.1.2

如果您收到端口已被使用的错误消息,您可以在 windows 上解决此问题的方法是

Go to the Task Manager.

Scroll and find a task process named. Node.js: Server-side

End this particular task.

在 npm 脚本中设置端口号根本不是个好主意。

您可以从终端使用以下命令传递端口号

SET PORT=3001 && npm start

通过 .env 文件使用环境变量的解决方法

多亏了这个github comment

用于开发

  1. 在项目根目录中为您的开发环境创建一个脚本,例如dev-server.js
// dev-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-dev');

cli.nextDev(['-p', process.env.PORT || 3000]);
  1. 然后您可以在 .env 中设置自定义端口,如下所示:PORT=3002

  2. 更新 package.json 中的开发命令以使用 dev-server.js 脚本,如下所示:

  "scripts": {
    "dev": "node dev-server.js"
  }
  1. 运行 npm run dev NextJS 应用程序将在端口 3002 上启动。

生产用

  1. 在项目根目录中为您的生产环境创建一个脚本,例如prod-server.js
// prod-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-start');

cli.nextStart(['-p', process.env.PORT || 3000]);
  1. 然后您可以在 .env 中设置自定义端口,如下所示:PORT=3002

  2. 更新 package.json 中的启动命令以使用 prod-server.js 脚本,如下所示:

  "scripts": {
    "build": "next build",
    "start": "node prod-server.js"
  }
  1. 运行 npm run start 并且 NextJS 应用程序将在端口 3002 上启动。(不要忘记在 npm run build 之前构建项目)

dotenv 应通过 npm install dotenv 安装,需要并在脚本中配置,如之前的代码片段所示。

来自 github comment 的注释:

There are some hosting providers that just force us to have server.js/index.js file. The bonus of the above solution is that it doesn't require any additional dependency.

使用 yarn 您可以轻松传递任何参数:
yarn dev -p 8080yarn dev --port=8080.

npm一起使用--传递参数:
npm run dev -- -p 8080