Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react import environment in setupProxy.js of http-proxy-middleware generate unexpected identifier

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! [email protected] startlocal: cross-env CLIENT_ENV=local craco start
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] 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.

like image 721
giorgiogalassi76 Avatar asked Dec 14 '25 18:12

giorgiogalassi76


1 Answers

You don't need setupProxy.js and http-proxy-middleware.

Just add proxy to your current craco.config.js:

module.exports = {
...
    devServer: {
        proxy: {
            '/api': 'http://localhost:5000'
        }
    }
};

more info about devServer settings: https://webpack.js.org/configuration/dev-server/#devserverproxy

like image 75
Victor Trusov Avatar answered Dec 18 '25 06:12

Victor Trusov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!