Pass env vars to react via webpack

Elvis Ciotti
Apr 17, 2022

--

When loaded via webpack, REACT_APP_ variable are not visible from react components.

To make custom variable vibible inside tsx files, define them in webpack via the DefinePlugin.

# webpack.config.js.. here you can read the process.env.variables from nodeconst PROCESS_ENV_NODE_ENV = process.env.NODE_ENV ? process.env.NODE_ENV : 'local';module.exports = {
...
new webpack.DefinePlugin({
...
'process.env.REACT_APP_ENVIRONMENT': JSON.stringify(PROCESS_ENV_NODE_ENV),
}),
...
};
The you can read them in react by accessing`process.env.REACT_APP_ENVIRONMENT`Note 1: In my current version, it didn't work with variable named PROCESS_ENV
Note 2: the prefix process.env is mandatory for the variable

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet