Variables related to the environment within babel.config.js

We are in need of adjusting specific configuration/variables within our React Native app (created with Expo) based on the environment (local/dev/staging/production). After exploring various libraries designed for this purpose, we have encountered issues that do not align with our requirements:

  • dotenv (issues arise as it attempts to access 'fs' at runtime, which is no longer available due to being a non-pure JS package that cannot be bundled by Expo)
  • react-native-config (cannot be integrated with Expo since it requires native code as part of the plugin)
  • react-native-dotenv (partially functions but internally caches config and does not recognize any .env changes until the importing file is modified)

Instead of relying on third-party plugins, I am contemplating utilizing babel's env option and creating separate JSON objects for each environment within babel.config.js. However, there seems to be limited documentation or examples regarding this approach. Should I simply include an env field on the same level as presets and plugins, containing production, development, etc. fields as shown in the example below:

module.exports = (api) => {
    api.cache(true);
    return {
        presets: [...],
        env: {
            development: {
                CONFIG_VAR: 'foo'
            },
            production: {
                CONFIG_VAR: 'bar'
            }
        }
    }
}

Would this method be effective? And how can I access the CONFIG_VAR later in the code?

Answer №1

I recently encountered similar issues while setting up environment variables in my Expo project. I found a solution by using a helpful tool called babel-plugin-inline-dotenv.

  1. Begin by installing the plugin:

     npm install babel-plugin-inline-dotenv
    
  2. Add the plugin and specify the path to the .env file in your babel.config.js file.

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    env: {
      production: {
        plugins: [["inline-dotenv",{
          path: '.env.production'
        }]]
      },
      development: {
        plugins: [["inline-dotenv",{
          path: '.env.development'
        }]]
      }
    }
  };
};

  1. In your .env.production or .env.development files, add environment variables in this format:

     API_KEY='<YOUR_API_KEY>'
    
  2. You can then access these variables in your code like so:

     process.env.API_KEY
    

To access your environment variables within the babel.config.js file, utilize the dotenv package in the following manner:

   require('dotenv').config({ path: './.env.development' })
   console.log('API_KEY: ' + process.env.API_KEY)

   module.exports = function() {
   // ...
   }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some strategies to enhance the performance of the following Mongoose query?

Essentially, I am trying to retrieve data from a collection where the pincode field (inside the Location array) matches the value from req.body. I am able to obtain the desired output, but I am unsure if this is the most optimized method or not (please see ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...

Utilizing jQuery to send multiple values via an ajax request

I am looking to modify this script to send multiple values using AJAX instead of just a single value. files.php $(".search_button").click(function() { var search_word = $("#search_box").val(); var dataString = 'search_word='+ search_word ...

The datepicker is refusing to update the date format

I've been attempting to adjust the date format for my datepicker, but it refuses to change. Below is the code I'm using: $(document).ready(function() { $('#dateselect').datepicker({ format: 'dd/mm/yyyy', o ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

I am getting text content before the input element when I log the parent node. What is causing this issue with the childNodes

Does anyone know why 'text' is showing up as one of the childNodes when I console.log the parent's childNodes? Any tips on how to fix this issue? <div id="inputDiv"> <input type="text" id="name" placeholder="Enter the nam ...

Ajax external variable

I successfully uploaded a json file via Ajax using vanilla JS. { "list": [ {"name": "Executor", "date": "19.04.2017, 12:32:57"}, ... ] } Although I am able to change the "date" value for the current one using addEventListener, my challenge no ...

"Utilizing Vuex: Fetch data from API when the first getter is accessed, and subsequently retrieve it from the local

I have a Vuex instance that is responsible for fetching data from an API. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas. This is th ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

Using jQuery to gradually fade out my sidebar (div)

I have written the following code to hide my sidebar when the screen width is less than 1024 pixels, but it doesn't seem to be working. It worked fine on a previous website, so I'm not sure what the issue is here. Any help would be greatly apprec ...

Is there a way to adjust a simple program using Discord.js where the setTimeout within a for-loop can print values sequentially instead of simultaneously?

Here is the code I'm using: for (let i = 0; i <= 5; i++) { delay(i); } function delay(i) { setTimeout(() => console.log(`${i} is the number`), 2000); } The output I'm currently getting after 2 seconds is: 0 is the number 1 is the ...

Issue with updating the notification badge on the menu bar

My website features a menu bar with a notification bubble badge created using CSS3. I have also implemented a PHP script to fetch the number of new messages from a MySQL database in my messenger inbox system. My goal is to dynamically update the value di ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

Unable to properly execute Fetch Delete Request

When using the Fetch API, I am sending this request: const target = e.currentTarget; fetch(target.href, { method: 'delete', }) .then(res => console.log(22)) .catch(err => console.log(err)); In addition, here is the middleware that manag ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

TS2339: The 'map' property is not available on the 'Object' type

I'm currently working with the following code snippet: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/op ...

React - The `component` prop you have supplied to ButtonBase is not valid. Please ensure that the children prop is properly displayed within this customized component

I am attempting to use custom SVG icons in place of the default icons from Material UI's Pagination component (V4). However, I keep encountering this console error: Material-UI: The component prop provided to ButtonBase is invalid. Please ensure tha ...