gpt4 book ai didi

reactjs - 如何配置我的 package.json 文件以从操作系统中设置的环境变量读取?

转载 作者:行者123 更新时间:2023-12-03 14:15:44 25 4
gpt4 key购买 nike

我正在使用 React 16.12.0。我在 package.json 中配置了以下“代理”

{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://localhost:9090",

这对于开发非常有用,但是当我将站点转移到质量保证和生产时,我希望能够从某种环境变量中读取我的 package.json 文件。如何编写我的 package.json 或将我的应用程序配置为根据环境使用不同的 URL,或者至少在我的环境中设置一个变量?

最佳答案

来自文档:https://create-react-app.dev/docs/proxying-api-requests-in-development/

Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.

作为替代方案,您可以使用环境变量:https://create-react-app.dev/docs/adding-custom-environment-variables/

您应该在项目的根目录下创建 .env.development.env.product 文件:

# .env.development

REACT_APP_PROXY=http://localhost:9090
# .env.production
REACT_APP_PROXY=<some other domain>

并在 react 应用程序上使用它:

// anywhere in the react app
const REACT_APP_PROXY = process.env.REACT_APP_PROXY

关于reactjs - 如何配置我的 package.json 文件以从操作系统中设置的环境变量读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60644619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com