简体   繁体   中英

environment variables in babel.config.js

We need to modify certain configuration/variables in our React Native app (built using Expo) depending on environment (local/dev/staging/production). I've looked at a number of libraries meant for this purpose but all seem to have a flaw that breaks for our use case:

  • dotenv (breaks because it tries to access 'fs' at runtime, when it's no longer available since it's not pure JS package and can't be bundled by Expo)
  • react-native-config (can't use it with Expo because it needs native code as part of the plugin)
  • react-native-dotenv (kinda works but caches config internally and ignores any .env changes until the file importing the variable is modified)

As a cleaner alternative that does not require third party plugins, I'm considering using babel's env option and just listing all of the environments as separate json objects within babel.config.js . I'm not seeing much documentation or examples on this, however. Do I just add env field at the same level as presets and plugins that contains production , development , etc. fields as in example below:

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

Would that work? And how would I access this CONFIG_VAR later in the code?

I just ran into the same issues when trying to setup environment variables in my Expo project. I have used babel-plugin-inline-dotenv for this.

  1. Install the plugin

     npm install babel-plugin-inline-dotenv
  2. Include the plugin and 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 like this:

     API_KEY='<YOUR_API_KEY>'
  2. Later in your code you can access the above variable like this:

     process.env.API_KEY

To access your env variables within the babel.config.js file, use the dotenv package like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM