Search code examples
reasonreason-react

How do you use environment variables in a ReasonReact app?


I tried adding a .env file to the root of my directory and I tried accessing the contents with

[@bs.val] external graphqlUrl : string = "process.env.GRAPHQL_URL";

but it when I Js.log(graphqlUrl); it's undefined!

.env file:

GRAPHQL_URL=https://api.example.com

How do I access it?

Thank you!


Solution

  • I followed sir Rem Lampa's suggestion and installed dotenv-webpack on my project. Then I followed the instructions on the dotenv-webpack docs.

    The webpack.config.js file now looks like this:

    const path = require('path');
    const outputDir = path.join(__dirname, "build/");
    
    const isProd = process.env.NODE_ENV === 'production';
    
    const Dotenv = require('dotenv-webpack');
    
    module.exports = {
      entry: './src/Index.bs.js',
      mode: isProd ? 'production' : 'development',
      output: {
        path: outputDir,
        publicPath: outputDir,
        filename: 'Index.js',
      },
      plugins: [
        new Dotenv()
      ]
    };