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:
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.
Install the plugin
npm install babel-plugin-inline-dotenv
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' }]] } } }; };
In your .env.production or .env.development files add environment variables like this:
API_KEY='<YOUR_API_KEY>'
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.