PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

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

 August 19, 2022     environment-variables, gitignore, google-maps, reactjs, webpack     No comments   

Issue

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.



Answered By - Tbot
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing