Search code examples
reactjsgoogle-mapswebpackenvironment-variablesgitignore

How do you reference a process.env variable in HTML <script src="" ? React


I have a react app and am using dotenv-webpack to manage my API keys.

I have: - created a .env with the API keys and gitignored it. - required and added dotenv as a plugin in webpack.config.js.

After that, I've been able to reference one of the keys in a .js file by using process.env.api_key. But I am having problems trying to reference it in index.html in the script tag.

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/style/style.css">
    <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
    <script src="https://maps.googleapis.com/maps/api/js?key=process.env.GOOGLEMAP_API_KEY"></script>
  </head>
  <body>
    <div class="container"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

How do I reference the process.env.API_key here?

<script src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]"></script>

I have tried using backquotes that work in .js file, like so ${API_KEY}, but that does not work in the .html file.


Solution

  • I put the following code in componentWillMount where the map renders and it worked (at least in development: const API_KEY = process.env.GOOGLEMAP_API_KEY; const script = document.createElement('script'); script.src = https://maps.googleapis.com/maps/api/js?key=${API_KEY}; document.head.append(script);

    I was able to get this to work using the code posted by bigmugcup in the comments above. I did not modify the webpack.config.js file.