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

How can I change the default port in react from 3000 to another port?

1个答案

1

When developing with React, the development server runs by default on port 3000. However, if this port is already in use by another service or for other reasons you need to change the port, you can easily change it to another port.

Changing the default port for a React application can be achieved by modifying the startup script. This is primarily done by setting the environment variable PORT. Here are several methods to set this environment variable:

Method 1: Set Directly in the Command Line

You can specify the PORT environment variable directly in the command line when starting the application. For example, if you are using npm as your package manager, you can do:

bash
PORT=5000 npm start

This command sets the port for the React application to 5000. If you use Yarn, the corresponding command is:

bash
PORT=5000 yarn start

Method 2: Modify package.json

Another common method is to modify the scripts section in package.json. This way, the new port is automatically used each time you start the application, eliminating the need to set it manually each time. You can modify it as follows:

json
{ "scripts": { "start": "PORT=5000 react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" } }

Here, we modified the start script to set the PORT environment variable to 5000.

Method 3: Use .env File

For more persistent environment variable settings, you can use a .env file. Create a file named .env in the project root directory and add the following content:

shell
PORT=5000

This way, every time you start the project, create-react-app will automatically read the settings from the .env file.

Example Use Case

Suppose you are developing a project that includes a backend API and a frontend React application. The backend API is using port 3000, so you need to change the React application's port to 5000. After changing the port using any of the above methods, you can run both services simultaneously without port conflicts.

In summary, changing the port is a simple process that can be accomplished in multiple ways. Choose the method that best suits your project requirements and preferences.

2024年6月29日 12:07 回复

你的答案