如何在next.js中设置端口

问题描述 投票:0回答:14

一个应用程序正在端口 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

javascript reactjs npm port next.js
14个回答
388
投票

这对我有用

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

75
投票
"scripts": {
    "dev": "next dev -p 8080", // for dev 
    "start": "next start -p 8080" // for prod
},

26
投票

只需要做:

yarn dev -p PORT_YOU_LIKE

26
投票

应用程序默认从 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.

23
投票

使用

yarn
pnpm
,您可以轻松传递任何参数:
yarn dev -p 8080
yarn dev --port=8080

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


15
投票

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

感谢这个github评论

为了发展

  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 命令以使用
    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 评论的注释

有些托管提供商只是强制我们拥有 server.js/index.js 文件。上述解决方案的好处是它不需要任何额外的依赖。


13
投票

有两种方法可以做到这一点:

在您的

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 文档 了解更多信息。


5
投票

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

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

SET PORT=3001 && npm start

5
投票

通常,端口是特定于环境的,因此不应转到 git 存储库。因此,最佳实践是在

.env.local
中定义它,并且可以使用以下启动脚本从那里读取它:

// package.json
"scripts": {
  "start": "[ -e .env.local ] && set -a && . ./.env.local; next start",
},

使用

set -a
将导出源环境变量,Next.JS 启动脚本将使用
PORT
环境变量(如果已定义)。请注意,此脚本在 Windows 中不起作用。


0
投票

以下示例适用于 nextjs 和 pm2 组合 pm2 启动 npx --name "next" -- next -p 3001


0
投票

另一种方法是在 Next.js 中使用自定义服务器文件

因此您只需在 env 文件中设置端口即可,而不必在其他任何地方进行更改。

像下面的例子

const express = require('express');
const next = require('next');
const getConfig = require('../next.config');


const { basePath, port } = getConfig.publicRuntimeConfig;

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

app.prepare().then(() => {
  const app = express();

  app.use(express.json());
  app.use(express.urlencoded({ limit: '20kb', extended: false }));


  app.listen(3000, (err) => {
    if (err) throw err;
    console.log('server running on port: ' + 3000);
  });
});

0
投票

出于某种原因,https://stackoverflow.com/a/69780065/6831932中的答案对我不起作用,但失败了

/path/to/project/node_modules/next/dist/bin/next:147
commands[command]().then((exec)=>exec(forwardedArgs)
                                 ^

TypeError: exec is not a function
    at /path/to/project/node_modules/next/dist/bin/next:147:34
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v19.8.1
npm ERR! Lifecycle script `dev` failed with error:
npm ERR! Error: command failed
npm ERR!   in workspace: [email protected]
npm ERR!   at location: /path/to/project/apps/frontend

我的解决方法是使用

node:child_process
来生成下一个:


const dotenv = require('dotenv');
// For some reason trying to invoke nextDev() from 'next/dist/cli/next-dev'
// doesn't work, even though others report success with it.
// So, let's try invoking `next` as a child process...
const {spawn} = require('node:child_process');

// I have a monorepo with node_modules and .env only at project root.
// If you don't, you can remove the '/../../' part.
const projectRoot = process.cwd() + '/../../';

// Get the .env file from the root of the project.
dotenv.config({path: projectRoot + '.env'});

// Get next binary path and default args.
const nextPath = projectRoot + 'node_modules/.bin/next';
const FRONTEND_PORT = process.env.FRONTEND_PORT || '4000';
const FRONTEND_HOST = process.env.FRONTEND_HOST || 'localhost';
const nextArgs = [
  'dev',
  '-p', FRONTEND_PORT,
  '-H', FRONTEND_HOST,
];

// Spawn next process.
const next = spawn(nextPath, nextArgs);

// Log output from next process.
next.stdout.on('data', (data) => {
  if (typeof data === 'string') {
    console.log(data);
  } else {
    console.log(data.toString());
  }
});

// Log errors from next process.
next.stderr.on('data', (data) => {
  if (typeof data === 'string') {
    console.error(data);
  } else {
    console.error(data.toString());
  }
});

0
投票

对于 NextJS 13,您所要做的就是在终端中指定它。运行:

npm run dev -p 4000

在端口 4000 上运行应用程序


-3
投票

除了在

package.json
中硬编码之外,您还可以通过
.env
文件来完成:

PORT=4000
© www.soinside.com 2019 - 2024. All rights reserved.