Yes, as Jhonnatan says, you can use the transform-inline-environment-variables
plugin. I'll show you.
First, install the dependency.
npm install --save-dev babel-plugin-transform-inline-environment-variables
Then, add the plugin to your babel.config.js
file. It would look something like this:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: ['transform-inline-environment-variables'],
};
};
After that I recommend creating a .env
file in your project, for example, to a API URL base, in this case, for a server running locally in your machine:
API_URL_BASE = http://10.0.2.2:3001
Remember that the .env
file shouldn't be pushed to GitHub, because that is usually where we store sensitive data.
At this point, you can use environment variables directly in your source code, with process.env.API_URL_BASE
. Literally anywhere in your code. When you modify babel.config.js
, you should always restart the development server and clear the cache, so start your project with npx expo start --clear
.
Okey, but what happened if I want to use another API_URL_BASE
in production (EAS Build)
? No problem, you need to add a secret
to your EAS project.
Go to your project (https://expo.dev/accounts/my-username/projects/my-project) and in the Dashboard choose Secrets
.
Then Create
.
Finally, set the name of the secret (same as the .env
file) and the value that you want for production environment.
And that's it! When you develop on your local machine, it will use the API_URL_BASE
from your .env
file, and when you build your app, EAS will take the API_URL_BASE
from the secrets.
I hope that works for you! Any questions are available. Regards :)
process.env.VARIABLE_NAME
from Node.js or in shell scripts as$VARIABLE_NAME
." – Lungworm