Skip to content

Commit

Permalink
🧑‍💻 [#724] Handle env reading/processing in both Vite and CRA setups
Browse files Browse the repository at this point in the history
We can detect the environment based on the presence of 'process' or
not, and adapt the reading of environment variables based on the
detected environment.

This means that we currently have to duplicate the configuration,
but as long as this is a temporary measure, we should be fine.
  • Loading branch information
sergei-maertens committed Nov 29, 2024
1 parent ec850d5 commit f3f66d3
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 17 deletions.
7 changes: 7 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# ViteJS based
VITE_VERSION=latest
VITE_BASE_API_URL=http://localhost:8000/api/v2/
VITE_FORM_ID=93c09209-5fb9-4105-b6bb-9d9f0aa6782c
VITE_USE_HASH_ROUTING=false

# Legacy
REACT_APP_VERSION=latest
REACT_APP_BASE_API_URL=http://localhost:8000/api/v2/
REACT_APP_FORM_ID=93c09209-5fb9-4105-b6bb-9d9f0aa6782c
Expand Down
3 changes: 2 additions & 1 deletion src/api-mocks/base.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {getEnv} from 'env';
import cloneDeep from 'lodash/cloneDeep';
import set from 'lodash/set';

export const BASE_URL = process.env.REACT_APP_BASE_API_URL || 'http://localhost:8000/api/v2/';
export const BASE_URL = getEnv('BASE_API_URL') || 'http://localhost:8000/api/v2/';

/**
* Create a function to build an object from a default with optional overrides.
Expand Down
4 changes: 2 additions & 2 deletions src/components/Literal.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import PropTypes from 'prop-types';
import React, {useContext} from 'react';

const isDevelopment = process.env.NODE_ENV === 'development';
import {DEBUG} from 'utils';

const LiteralContext = React.createContext();
LiteralContext.displayName = 'LiteralContext';
Expand All @@ -24,7 +24,7 @@ const EMPTY_LITERAL = {resolved: ''};
const Literal = ({name}) => {
const literals = useContext(LiteralContext);
const value = (literals[name] || EMPTY_LITERAL).resolved;
if (isDevelopment && !value) {
if (DEBUG && !value) {
console.warn(`Literal ${name} not found!`);
}
return value;
Expand Down
34 changes: 34 additions & 0 deletions src/env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Handle the env in both (legacy) CRA and the new Vite-based setup.
*
* CRA is `process.env` based, using NodeJS, while ViteJS used import.meta from the
* module system.
*/

let env;
let envVarPrefix = 'VITE';

let DEBUG = false;

// Support both CRA and Vite for the time being.
try {
env = process.env;
// it's legacy create-react-app
DEBUG = env.NODE_ENV === 'development';
envVarPrefix = 'REACT_APP';
} catch (error) {
if (error instanceof ReferenceError) {
// it's ViteJS, which doesn't know `process`
env = import.meta.env;
DEBUG = env.MODE === 'development';
} else {
throw error;
}
}

const getEnv = name => {
const fullName = `${envVarPrefix}_${name}`;
return env[fullName];
};

export {DEBUG, env, getEnv};
5 changes: 2 additions & 3 deletions src/hooks/usePageViews.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import {useContext, useEffect, useRef} from 'react';
import {useLocation} from 'react-router-dom';

import {ConfigContext} from 'Context';

const isDev = process.env.NODE_ENV === 'development';
import {DEBUG} from 'utils';

function usePrevious(value) {
const ref = useRef({
Expand All @@ -25,7 +24,7 @@ function usePrevious(value) {

const ANALYTICS_PROVIDERS = {
debug: async location =>
isDev &&
DEBUG &&
console.log(
`Tracking navigation to ${window.location.origin + location.pathname}${location.hash}`
),
Expand Down
14 changes: 8 additions & 6 deletions src/index.jsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import {getEnv} from 'env';

import './index.scss';
import {OpenForm} from './sdk';

// import displayComponents from './custom-display-components';

const {REACT_APP_BASE_API_URL, REACT_APP_FORM_ID, REACT_APP_USE_HASH_ROUTING} = process.env;
const BASE_API_URL = getEnv('BASE_API_URL');
const FORM_ID = getEnv('FORM_ID');
const USE_HASH_ROUTING = getEnv('USE_HASH_ROUTING');

window.onload = () => {
const formId = new URLSearchParams(document.location.search).get('form');
const targetNode = document.getElementById('root');
const form = new OpenForm(targetNode, {
baseUrl: REACT_APP_BASE_API_URL,
formId: formId || REACT_APP_FORM_ID,
baseUrl: BASE_API_URL,
formId: formId || FORM_ID,
basePath: '/',
// added for testing purposes - adding a real CSP breaks *a lot* of things of Create
// React App :(
CSPNonce: 'RqgbALvp8D5b3+8NuhfuKg==',
// displayComponents,
useHashRouting: REACT_APP_USE_HASH_ROUTING === 'true' || false,
useHashRouting: USE_HASH_ROUTING === 'true' || false,
});
form.init();
};
10 changes: 5 additions & 5 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import classNames from 'classnames';

import {getEnv} from './env';
import {applyPrefix} from './formio/utils';

export const DEBUG = process.env.NODE_ENV === 'development';
const {REACT_APP_VERSION} = process.env;
export {DEBUG} from './env';

const VERSION = getEnv('VERSION');

export const getFormattedDateString = (intl, dateString) => {
if (!dateString) return '';
Expand All @@ -24,6 +26,4 @@ export const getBEMClassName = (base, modifiers = []) => {
// usage: await sleep(3000);
export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

export const getVersion = () => {
return REACT_APP_VERSION || 'unknown';
};
export const getVersion = () => VERSION || 'unknown';

0 comments on commit f3f66d3

Please sign in to comment.