简体   繁体   English

如何使用 npm 在命令行中传递参数并在反应 javascript 代码中读取它

[英]How to pass argument in command line with npm and read it in react javascript code

I run the react application using npm start which in package.json is defined as "start": "react-scripts start -o" .我使用npm start运行反应应用程序,在 package.json 中定义为"start": "react-scripts start -o" in the js code I have在我的js代码中

const backendUrl = 'hardCodedUrl';

I want this property to be passed as CLI argument.我希望将此属性作为 CLI 参数传递。 like:喜欢:

npm start url=newUrl

and read this in the javascript code at runtime to be able to set backendUrl.并在运行时在 javascript 代码中阅读此内容,以便能够设置 backendUrl。 How Can I do this?我怎样才能做到这一点?

So I visited the link Andy sent and here is how I did it: Because I'm on Windows and using Terminal with PowerShell, run:所以我访问了 Andy 发送的链接,我是这样做的:因为我在 Windows 上并使用带有 PowerShell 的终端,运行:

$env:REACT_APP_TT_BACKEND_URL = "Thank you Andy"
npm start

In the code在代码中

console.log('REACT_APP_TT_BACKEND_URL', process.env.REACT_APP_TT_BACKEND_URL);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM