I need to set the target of proxy http-proxy-middleware in react using a variable obtained by craco. I have followed this guide to have more configuration file for different environments. I have 3 files local.js, development.js, and production.js that are selected by craco using different npm run startlocal, startdevelopment.
In package.json I have:
"scripts": {
"startlocal": "cross-env CLIENT_ENV=local craco start",
"startdevelopment": "cross-env CLIENT_ENV=development craco start",
"startproduction": "cross-env CLIENT_ENV=production craco start",
The problem is I want to change proxy in function of what environment I am and so using http-proxy-middleware I have used setupProxy.js as stated by guide. If I insert import environment from 'environment'; in setupProxy.js I have the error unexpected identifier.
This is the code of setupProxy.js:
import environment from 'environment';
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://localhost:5000/' }));
};
this my craco.config.js
const path = require('path');
module.exports = function({ env, paths }) {
return {
webpack: {
alias: {
environment: path.join(__dirname, 'src', 'environments', process.env.CLIENT_ENV)
}
},
};
};
Console output by npm run startlocal
Unexpected identifier
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! seltirmedfront_candidati@0.1.0 startlocal:cross-env CLIENT_ENV=local craco start
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the seltirmedfront_candidati@0.1.0 startlocal script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I suppose that the problem is linked to the fact that setupProxy.js is auto loaded and is loaded before craco.config.js so it doesn't have that import.