score:1

Accepted answer

After code diving, it appears the typescript create-react-app has not yet incorporated custom proxy functionality. I had to update two files:

https://github.com/samuelstevens9/create-react-app/blob/next/packages/react-scripts/config/paths.js

Added proxySetup: resolveApp('src/setupProxy.js'), to each module.exports, the last (3rd) being proxySetup: resolveOwn('template/src/setupProxy.js'),

https://github.com/samuelstevens9/create-react-app/blob/next/packages/react-scripts/config/webpackDevServer.config.js

Added const fs = require('fs'); below line 15 const paths = require('./paths'); and added

if (fs.existsSync(paths.proxySetup)) {
    // This registers user provided middleware for proxy reasons
    require(paths.proxySetup)(app);
}

inside the before(app) { ... } function towards the end of the file.

I am working on creating a pull request to the main repo, but it looks like the v3.1.0 files are different from the most up to date ones on the next branch. For now I use a patch script I made since we are using a lerna monorepo that updates all necessary packages:

#!/bin/bash
CONFIG_PATHS_URL="https://raw.githubusercontent.com/samuelstevens9/create-react-app/next/packages/react-scripts/config/paths.js"
CONFIG_WEBPACKDEVSERVER_URL="https://raw.githubusercontent.com/samuelstevens9/create-react-app/next/packages/react-scripts/config/webpackDevServer.config.js"
SETUPPROXY_URL="https://gist.githubusercontent.com/samuelstevens9/5872e72ac915dfc1a8ae2fdcef323899/raw/7f2c76d42bc0915026379dfc7884cb1bd97f56bb/setupProxy.js"

for f in packages/*; do
    if [ -d ${f} ]; then
        echo $f
        # Will not run if no directories are available
        NODE_MODULES_CONFIG_DIR=$f/node_modules/react-scripts-ts/config
        if [ -d "$NODE_MODULES_CONFIG_DIR" ]; then
          # Control will enter here if $DIRECTORY exists.
          echo $NODE_MODULES_CONFIG_DIR
          curl -o $NODE_MODULES_CONFIG_DIR/paths.js $CONFIG_PATHS_URL
          curl -o $NODE_MODULES_CONFIG_DIR/webpackDevServer.config.js $CONFIG_WEBPACKDEVSERVER_URL
          curl -o $f/src/setupProxy.js $SETUPPROXY_URL
        fi
    fi
done

And updates the setupProxy.js file in each package as well. Hope this helps.

score:1

Now CRA supports Typescript but I couldn't make setupProxy.js to work.

My mistake was super dumb. setupProxy was outside src/ folder. So, make sure that you create setupProxy inside the folder src

src/setupProxy.js

My code looks like this:

module.exports = function (app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: process.env.REACT_APP_API_URI,
      changeOrigin: true,
    })
  )
}

Also, make sure that your env configuration is working. You need to install the package env-cmd and replace

"start": "react-scripts start",

for

"start": "env-cmd -f .env.development.local react-scripts start",


Related Query

More Query from same tag