title: Cannot use process.env in React component, but can import it in webpack.config.js
body: <p>My React app is not built using 'create-react-app'.</p>
  
  <p>I am able to console.log from webpack.config.js the process environments i have imported and parsed from a .env file using dotenv library. </p>
  
  <p>However, 'npm run build' fails. When i substitute the variable with the URL string, 'npm run build' passes.</p>
  
  <p><strong>webpack.config.js</strong></p>
  
  <pre><code>const webpack = require('webpack');
  const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  const dotenv = require('dotenv').config({path: 'config/docker/production/.env'});
  
  // call dotenv and it will return an Object with a parsed key 
  const env = dotenv.parsed;
  
  // reduce it to a nice object, the same as before
  const envKeys = Object.keys(env).reduce((prev, next) =&gt; {
  prev[`process.env.${next}`] = JSON.stringify(env[next]);
  return prev;
  }, {});
  
  console.log(process.env.API_URL); -&gt; prints out http://localhost:5000/api/something
  
  const config = {
      entry:  __dirname + '/static/js/index.jsx',
      output: {
          path: __dirname + '/static/dist',
          filename: 'bundle.js',
      },
      resolve: {
          extensions: [".js", ".jsx", ".css"]
      },
      module: {
          rules: [
              {
                  test: /\.jsx?/,
                  exclude: /node_modules/,
                  use: 'babel-loader'
              },
              {
                  test: /\.css$/,
                  use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']
              },
              {
                  test: /\.(png|svg|jpg|gif)$/,
                  use: 'file-loader'
              }
          ]
      },
      plugins: [
          new MiniCssExtractPlugin({
              path: __dirname + '/static/dist',
              filename: 'styles.css',
          }),
          new webpack.DefinePlugin(envKeys)
      ]
  };
  
  module.exports = config;
  </code></pre>
  
  <p><strong>package.json</strong></p>
  
  <pre><code>  "scripts": {
      "build": "webpack --mode production -p --progress --config webpack.config.js"
    }
  </code></pre>
  
  <p><strong>config/docker/production/.env</strong></p>
  
  <pre><code>API_URL=http://]ocalhost:5000/api/something
  </code></pre>
  
  <p><strong>MyComp.jsx</strong></p>
  
  <pre><code>import React,{ Component } from 'react';
  
  class MyComp extends Component {
    constructor(props) {
      super(props);
      this.state = {
        races: []};
    }
  
    componentDidMount(){
      fetch({process.env.API_URL}) -&gt; FAILS
      fetch('http://localhost:5000/api/something') -&gt; PASSES
        .then(results =&gt; results.json()) 
        .then(data =&gt; this.setState({ races: data.data }));
  
    }
  
    render() {
        ...
    }
  }
  
  export default MyComp;
  </code></pre>