doyz
doyz

Reputation: 886

Cannot use process.env in React component, but can import it in webpack.config.js

My React app is not built using 'create-react-app'.

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.

However, 'npm run build' fails. When i substitute the variable with the URL string, 'npm run build' passes.

webpack.config.js

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) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});

console.log(process.env.API_URL); -> 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;

package.json

  "scripts": {
    "build": "webpack --mode production -p --progress --config webpack.config.js"
  }

config/docker/production/.env

API_URL=http://]ocalhost:5000/api/something

MyComp.jsx

import React,{ Component } from 'react';

class MyComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      races: []};
  }

  componentDidMount(){
    fetch({process.env.API_URL}) -> FAILS
    fetch('http://localhost:5000/api/something') -> PASSES
      .then(results => results.json()) 
      .then(data => this.setState({ races: data.data }));

  }

  render() {
      ...
  }
}

export default MyComp;

Upvotes: 1

Views: 3999

Answers (2)

Moniruzzaman Monir
Moniruzzaman Monir

Reputation: 121

Drop 'process.env' from line 10 in your webpack config file

prev[`process.env.${next}`] = JSON.stringify(env[next]);

to

prev[`${next}`] = JSON.stringify(env[next]);

and use the 'API_URL' variable directly without process.env.

you can read webpack documentation of DefinePlugin here

another issue might be how you are using 'process.env.API_URL'. it should be:

fetch(`${process.env.API_URL}`)

see the tick and dollar sign.

Upvotes: 1

Soroush Chehresa
Soroush Chehresa

Reputation: 5678

You should use dotenv-webpack webpack plugin to expose environment variables to your React application.

Installation:

npm i -D dotenv-webpack

Usage:

// webpack.config.js

const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: 'config/docker/production/.env',
    }),
  ]
  ...
};

Upvotes: 1

Related Questions