如何指定一个端口来运行基于 create-react-app 的项目? [英] How to specify a port to run a create-react-app based project?
问题描述
我的项目基于 创建反应应用.npm start
或 yarn start
默认会在端口 3000 上运行应用程序,并且在 package.json 中没有指定端口的选项.
My project is based on create-react-app. npm start
or yarn start
by default will run the application on port 3000 and there is no option of specifying a port in the package.json.
在这种情况下如何指定我选择的端口?我想同时运行这个项目的两个(用于测试),一个在端口 3005
另一个是 3006
How can I specify a port of my choice in this case? I want to run two of this project simultaneously (for testing), one in port 3005
and other is 3006
推荐答案
如果你不想设置环境变量,另一种选择是修改 package.json 的 scripts
部分:
If you don't want to set the environment variable, another option is to modify the scripts
part of package.json from:
"start": "react-scripts start"
到
Linux(在 Ubuntu 14.04/16.04 上测试)和 MacOS(由 @aswin-s 在 MacOS Sierra 10.12.4 上测试):
Linux (tested on Ubuntu 14.04/16.04) and MacOS (tested by @aswin-s on MacOS Sierra 10.12.4):
"start": "PORT=3006 react-scripts start"
或者(可能是)@IsaacPak 提供的更通用的解决方案
or (may be) more general solution by @IsaacPak
"start": "export PORT=3006 react-scripts start"
Windows @JacobEnsor 解决方案
Windows @JacobEnsor solution
"start": "set PORT=3006 && react-scripts start"
cross-env lib 适用于任何地方.有关详细信息,请参阅 Aguinaldo Possatto 答案
cross-env lib works everywhere. See Aguinaldo Possatto answer for details
由于我的回答受欢迎而更新:目前我更喜欢使用保存在 .env
文件(用于以方便和可读的形式存储不同deploy
配置的变量集).如果您仍将机密存储在 .env
文件中,请不要忘记将 *.env
添加到 .gitignore
中.这里解释了为什么在大多数情况下使用环境变量更好.这里解释为什么在环境中存储秘密是个坏主意.
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.
这篇关于如何指定一个端口来运行基于 create-react-app 的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!