是否可以在 CRA 中以不同于 package.json 的方式设置代理设置?例如使用 ENV 变量?
来自 CRA docs它指出
Use environment variables to inject the right server host and port into your app.
这句话是关于代理还是开发服务器本身?
最佳答案
Note: this feature is available with react-scripts@2.0.0 and higher.
您现在可以手动配置代理。您需要先安装http-proxy-middleware
。
npm install http-proxy-middleware --save
然后创建一个包含以下内容的文件 src/setupProxy.js
。
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api', // You can pass in an array too eg. ['/api', '/another/path']
createProxyMiddleware({
target: process.env.REACT_APP_PROXY_HOST,
changeOrigin: true,
})
);
};
您现在可以在 .env
文件中添加代理,请记住您需要 REACT_APP_
前缀以便开发服务器获取环境变量。
REACT_APP_PROXY_HOST=http://localhost:5000
引用号:Proxy manually
关于reactjs - 如何在 Create React App Proxy 设置中使用 ENV 变量注入(inject)端口和主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686434/