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

If you're already using create-react-app, this is already available by updating to

<script src="https://maps.googleapis.com/maps/api/js?key=%REACT_APP_API_KEY%"></script>

as it says in the docs

You can also access the environment variables starting with REACT_APP_ in the public/index.html.


The simple way you can use

in HTML

<p>%NODE_ENV%</p>

and in script

<script>
if('%NODE_ENV%' === 'production') {
.... some code
}
</script>

Solution

You can't reference the process.env variable directly inside html.

Create your own template from index.html and replace the api url with a parameter.

HtmlWebpackPlugin

Simplifies creation of HTML files to serve your webpack bundles.

You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.

Webpack.config.js

HtmlWebpackPlugin allows you to create and pass parameters to your template:

   const api_key = process.env.api_key;
   const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: 'index.js',
      plugins: [
        new HtmlWebpackPlugin({
          inject: false,
          template: './template.html',

          // Pass the full url with the key!
          apiUrl: `https://maps.googleapis.com/maps/api/js?key=${api_key}`,

        });
      ]
    }

template.html

Inside the template you can access to the parameter:

<script src="<%= htmlWebpackPlugin.options.apiUrl %>"></script>

See: Writing Your Own Templates

Notes

This is a modified answer from this comment, please read the full conversation.


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.