我的项目是基于创建-反应-应用程序。NPM启动或yarn启动默认将在端口3000上运行应用程序,在package.json中没有指定端口的选项。

在这种情况下,如何指定自己选择的端口?我想同时运行这个项目的两个(用于测试),一个在端口3005,另一个是3006


当前回答

你可以在package.json中修改你的脚本:

- MacOs:

"scripts": {
     "start": "PORT=9002 react-scripts start",
     "build": "react-scripts build",
     ...     
}

在窗户

  "scripts": {
      "start": "set PORT=9002 && react-scripts start",
      "build": "react-scripts build",
      ...
}

其他回答

如果你在Dockerfile中运行npm start,你不能在docker运行中映射端口,比如做一些类似-p 3001:3000的事情,这是有效的:

FROM node

ENV PORT=3001

# whatever here, COPY .. etc.

CMD npm start

或者你可以在docker build中传递端口号作为参数:

FROM node

ARG PORT=${PORT}
ENV PORT=${PORT}

# whatever here, COPY .. etc.

CMD npm start

在docker build中使用——build-arg

docker build --build-arg PORT=3001 .

对于我的windows朋友们,我发现了一种改变ReactJS端口的方法,可以在任何你想要的端口上运行。在运行服务器之前,请转到

 node_modules/react-scripts/scripts/start.js

在其中,搜索下面的行并将端口号更改为所需的端口

 var DEFAULT_PORT = process.env.PORT || *4000*;

这样就可以开始了。

编辑您的项目/包。json文件。

进入脚本部分。将开始键对应的值更新为以下内容。

"start": "export PORT=4000;react-scripts开始”

现在你的React应用程序将在http://localhost:4000/上运行

注意:您可以使用任何端口号,但最好避免众所周知的端口号,如22,21,80等。

您可以在启动应用程序时找到默认端口配置

yourapp/scripts/start.js

向下滚动并将端口更改为您想要的任何端口

const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 4000;

希望这对你有所帮助;)

在我的包里换衣服。“export PORT=3001 && react-scripts start”也适用于我,我在macOS 10.13.4上