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

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


当前回答

如果能够指定不是3000的端口(作为命令行参数或环境变量),那就太好了。

现在,这个过程相当复杂:

运行npm Run eject 等待它完成 编辑scripts/start.js,用你想使用的任何端口找到/替换3000 编辑config/webpack.config.dev.js并执行同样的操作 npm开始

其他回答

在Windows中可以通过两种方式实现。

在“\node_modules\react-scripts\scripts\start.js”下搜索 “DEFAULT_PORT”并添加所需的端口号。 例如:const DEFAULT_PORT = parseInt(process.env. port = parseInt)端口,10)|| 9999; 在包中。Json,追加下面的行。 "start": "set PORT=9999 && response -scripts start" 然后使用NPM start启动应用程序。它将在9999启动应用程序 端口。

对于windows操作系统,可直接在cmd命令下执行此命令

set PORT=3001 && npm start

在你的包裹里。在脚本中使用——port 4000或set port =4000,如下例所示:

包中。json (Windows):

"scripts": {
    "start": "set PORT=4000 && react-scripts start"
}

包中。json (Ubuntu):

"scripts": {
    "start": "export PORT=4000 && react-scripts start"
}

如果你已经做了npm run eject,去scripts/start.js并在const DEFAULT_PORT = parseInt(process.env. js)中更改port。端口,10)|| 3000;(在本例中为3000)到您想要的任何端口。

你可以在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",
      ...
}