facebook / metro

🚇 The JavaScript bundler for React Native
https://metrobundler.dev
MIT License
5.24k stars 626 forks source link

How does one access `EXPO_PUBLIC_XXX` environment variables in the `public/index.html` file? #1294

Open JPStrydom opened 5 months ago

JPStrydom commented 5 months ago

We're trying to migrate our web builder from Expo Webpack to Expo Metro.

We're quite far in our product development, so it's not feasible for us to migrate to Expo Router, so we're sticking with React Navigation. Our web app seems to build and work fine, but we've been unable to figure out how to access environment variables from our template HTML file.

The main reason that we need these env files available in our public/index.html file is to load scripts for certain tools, such as Google Maps.

We have a .env file with the following:

EXPO_PUBLIC_TEST_ENV=this-is-a-test

Throughout the React Native systems we can access this with:

process.env.EXPO_PUBLIC_TEST_ENV

But, the problem is that these environment variables don't seem to be available in the public/index.html file. We've tried adding the following to the public/index.html file, but none of it seems to work:

<script type="text/javascript">
  console.log('%EXPO_PUBLIC_TEST_ENV%'); // This just logs %EXPO_PUBLIC_TEST_ENV%
  console.log('%TEST_ENV%'); // This just logs %TEST_ENV%
  console.log('<%= EXPO_PUBLIC_TEST_ENV %>'); // This just logs <%= EXPO_PUBLIC_TEST_ENV %>
  console.log('<%= TEST_ENV %>'); // This just logs <%= TEST_ENV %>
  console.log(process); // This just logs undefined
</script>

Our metro.config.js file is simply:

const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);

module.exports = config;

So the question is, how does one access the env variables in the public/index.html file? We've been searching for near a month and haven't found a way to do this.

This is a big blocker for our Expo 51 migration, so any help would be greatly appreciated.