乐闻世界logo
搜索文章和话题

How to specify a port to run a create- react -app based project?

7 个月前提问
3 个月前修改
浏览次数101

6个答案

1
2
3
4
5
6

在使用create-react-app创建的React项目中,可以通过设置环境变量PORT来指定应用的运行端口。这里有几种方式可以设置这个环境变量:

使用命令行直接设置

在启动项目时,可以在命令行中直接指定PORT环境变量。例如在Unix系统(包括macOS和Linux)上,你可以使用以下命令:

bash
PORT=3001 npm start

而在Windows上,你可以使用set命令:

bash
set PORT=3001 && npm start

如果你使用的是Windows PowerShell,命令会有所不同:

powershell
$env:PORT=3001; npm start

使用.env文件

create-react-app支持加载项目根目录下的.env文件中的环境变量。你可以创建一个.env文件(如果还没有的话),然后在该文件中添加如下内容来指定端口:

shell
PORT=3001

每次运行npm start时,create-react-app都会加载.env文件中的环境变量。

综合示例

假设你的项目需要在端口3001上运行。你可以首先创建一个.env文件在你的项目根目录下(如果已经存在,就编辑它),然后添加如下内容:

shell
PORT=3001

保存文件后,每次你运行npm start,React开发服务器就会自动在端口3001上启动。

如果你偶尔需要在不同的端口上运行,你可以临时在命令行中覆盖.env文件中的设置,例如:

bash
PORT=3002 npm start

这样,即使.env文件中指定的是端口3001,应用也会在端口3002上启动。

请注意,端口只能指定一个未被使用的端口号。如果指定的端口已经被其他应用占用,React开发服务器会报错,告知该端口已被占用。

2024年6月29日 12:07 回复

If you don't want to set the environment variable, another option is to modify the scripts part of package.json from:

shell
"start": "react-scripts start"

to

Linux (tested on Ubuntu 14.04/16.04) and MacOS (tested by aswin-s on MacOS Sierra 10.12.4):

shell
"start": "PORT=3006 react-scripts start"

or (may be) more general solution by IsaacPak

shell
"start": "export PORT=3006 react-scripts start"

Windows JacobEnsor's solution

shell
"start": "set PORT=3006 && react-scripts start"

cross-env lib works everywhere. See Aguinaldo Possatto's answer for details

Update due to the popularity of my answer: Currently I prefer to use environment variables saved in .env file(useful to store sets of variables for different deploy configurations in a convenient and readable form). Don't forget to add *.env into .gitignore if you're still storing your secrets in .env files. Here is the explanation of why using environment variables is better in the most cases. Here is the explanation of why storing secrets in environment is bad idea.

2024年6月29日 12:07 回复

Here is another way to accomplish this task.

Create a .env file at your project root and specify port number there. Like:

shell
PORT=3005
2024年6月29日 12:07 回复

Create a file with name .env in the main directory besidespackage.json and set PORT variable to desired port number.

For example:

.env

shell
PORT=4200

You can find the documentation for this action here: https://create-react-app.dev/docs/advanced-configuration

2024年6月29日 12:07 回复

You could use cross-env to set the port, and it will work on Windows, Linux and Mac.

shell
yarn add -D cross-env

then in package.json the start link could be like this:

shell
"start": "cross-env PORT=3006 react-scripts start",
2024年6月29日 12:07 回复

Method 1

Create .env File in the root folder of a project

enter image description here

Set like this

shell
PORT=3005

Method 2

enter image description here

In package.json

shell
set PORT=3006 && react-scripts start
2024年6月29日 12:07 回复

你的答案