2

In my React (v17) app I would like to render API handlers differently depending on whether there is an process.env.REACT_APP_API_BASE defined.

So something in effect like

if (process.env.REACT_APP_API_BASE) {
  // use the actual API handler
  export { login, loginSilent, logout } from './api'
} else {
  // use the inline fake API handler
  export { login, loginSilent, logout } from './fake'
}

However trying that I get the error Parsing error: 'import' and 'export' may only appear at the top level.

Is there a standard way to selectively use one file or the other like this?

clarification

What I'm looking for is a way for Webpack or Babel to conditionally render one export or the other, rather than leaving both options inline in the code.

further clarification

I've tried to use various babel plugins and webpack overrides (using customize-cra etc) but none of that worked terribly well and seemed to introduce more problems.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134

1 Answers1

0

Try to split out the logic to make sure export appear at the top level.

import {
  login as loginMock,
  loginSilent as loginSilentMock,
  logout as logoutMock,
} from "./fake";
import {
  login as loginApi,
  loginSilent as loginSilentApi,
  logout as logoutApi,
} from "./api";
const [login, loginSilent, logout] = process.env.REACT_APP_API_BASE
  ? [loginMock, loginSilentMock, logoutMock]
  : [loginApi, loginSilentApi, logoutApi];
export { login, loginSilent, logout };
Hai Pham
  • 2,188
  • 11
  • 20
  • This will have the effect of webpack bundling up both the fake and real APIs. what I am after is not so much a conditional import as conditional code rendering by webpack or babel I think – Dave Sag Jan 11 '21 at 05:04