Next.js: 通过 next.config.js 配置主机名和端口的方法

7
我正在使用 next.js 9.5.x,并且正在寻找一种通过 next.config.js 配置主机名和端口的方法。我已经在文档中搜索过这方面的信息,但没有找到答案。
我已经在 next.config.js 文件中读取了一系列的 .env 文件来进行一些设置,并将其中一些环境变量传递给应用程序代码本身。我已经有了指定主机名和端口的环境变量,并希望重用它们来设置服务器/开发服务器的主机名和端口。
为更改这两个参数,我找到的唯一两个解决方案是使用 next 的命令行设置或使用自定义 server.js。目前,我正在使用自定义 server.js,并在其中再次读取所有 .env 文件,以便设置端口和主机名。
我想要摆脱 server.js,因为我相信必须有一种通过 next.config.js 文件来配置这个的方法,而我已经准备好了一切。
感谢您提供相关信息。

你能找到一种方法吗? - Bri4n
3个回答

2

更改端口:

package.json 中,=> scripts => 添加 "dev": "next dev -p 5500"

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

enter image description here

*我找不到如何更改主机名。


1
之前我误解了问题,所以我只是更正了我的答案... - Ashutosh kumar

1

您可以使用-H来指定主机。 这是来自next dev的帮助信息:

Description
        Starts the application in development mode (hot-code reloading, error
        reporting, etc)

      Usage
        $ next dev <dir> -p <port number>

      <dir> represents the directory of the Next.js application.
      If no directory is provided, the current directory will be used.

      Options
        --port, -p      A port number on which to start the application
        --hostname, -H  Hostname on which to start the application (default: 0.0.0.0)
        --help, -h      Displays this message

-3

最好、最简单的配置方式是使用域名。您需要将下面的代码粘贴到您的next.config.js文件中,并添加域名:

images: {
domains: ["example.domain.com"],
},

图片优化配置对所提出的问题没有影响,这个问题是关于 Next.js 服务器本身的。 - evelynhathaway

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接