react-app-constants

Build variants for React apps

MIT License

Downloads
20
Stars
0
Committers
1

react-app-constants

Build variants for React apps

Name Description Version
react-app-constants Get constants with a hook npm
webpack-html-app-constants Inject application constants to HTML npm
webpack-html-powerstrip Create different version index.htmls npm

Get started

Requirements

Configure webpack and constants

$ yarn add --dev webpack-html-app-constants
$ yarn add react-app-constants
// config-overrides.js
const {
  rewire: rewireWithAppConstants,
} = require("webpack-html-app-constants");

module.exports = function override(config, env) {
  const variants = ["production", "qa"];
  return rewireWithAppConstants(config, env, { variants });
};
$ cat .env
REACT_APP_BFF_URL=https://bff-local.example.com/

$ cat .env.qa
REACT_APP_BFF_URL=https://bff-qa.example.com/

$ cat .env.production
REACT_APP_BFF_URL=https://bff-production.example.com/
$ yarn build
$ ls build/*.html
build/index.production.html build/index.qa.html 

Use constants in React application

// ---- src/constants.ts ----
import { setupContext } from "react-app-constants";

export interface Constants {
  BFF_URL: string
}

const { ConstantsProvider, useConstants } = setupContext<Constants>();

export { ConstantsProvider, useConstants };


// ---- src/App.tsx ----
import React from "react";
import { ApolloProvider } from "@apollo/react-hooks";

import { ConstantsProvider, useConstants } from "./constants";

const App: React.FC = () => {
  const { BFF_URL } = useConstants();
  const client = new ApolloClient({ uri: BFF_URL });

  return (
    <ApolloProvider client={client}>
      { /* ... */ }
    </ApolloProvider>
  );
};

const AppWrapper: React.FC = () => (
  <ConstantsProvider>
    <App />
  </ConstantsProvider>
);

export default AppWrapper;