question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Environment Variables not available in index.html for webpack 5 builds (React)

See original GitHub issue

Current Behavior

In the NX docs, it states that you can access the environment variables in the index.html file like so: https://nx.dev/latest/react/guides/environment-variables#using-environment-variables-in-indexhtml

For a react app that uses webpack 5, this is not the case. It does not replace the placeholder with the environment variable in the .env file.

Expected Behavior

The environment variables should be injected into the index.html folder at build time.

Steps to Reproduce

  • Create a new NX repo with a react app: npx create-nx-workspace@latest
  • In the react app, add a .env file with a variable in e.g. NX_TEST_VARIABLE='xyz'
  • In the index.html file add the following tag to the body: <p>%NX_TEST_VARIABLE%</p>
  • Run nx serve app - observe that the env variable is populated on the screen
  • Now upgrade from webpack 4 to webpack 5 npx nx g @nrwl/web:webpack5
  • Run nx serve app again - observe that now the env var is not populated and you see: %NX_TEST_VARIABLE% instead

Failure Logs

No visible failure logs

Environment

NX report: Node : 14.17.3 OS : darwin x64 npm : 7.20.0

nx : Not Found @nrwl/angular : Not Found @nrwl/cli : 12.8.0 @nrwl/cypress : 12.8.0 @nrwl/devkit : 12.8.0 @nrwl/eslint-plugin-nx : 12.8.0 @nrwl/express : Not Found @nrwl/jest : 12.8.0 @nrwl/linter : 12.8.0 @nrwl/nest : Not Found @nrwl/next : Not Found @nrwl/node : Not Found @nrwl/nx-cloud : Not Found @nrwl/react : 12.8.0 @nrwl/schematics : Not Found @nrwl/tao : 12.8.0 @nrwl/web : 12.8.0 @nrwl/workspace : 12.8.0 @nrwl/storybook : 12.8.0 @nrwl/gatsby : Not Found typescript : 4.3.5

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:15 (4 by maintainers)

github_iconTop GitHub Comments

4reactions
adambrgmncommented, Sep 7, 2021

I’m not really sure how to fix the issue. But we created a workaround for our project since we needed some conditional rendering in our index.html (scripts injected if env variable is defined and so on). Maybe it could fit your needs as well.

  1. Create a webpack.config.js in your apps root folder:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (config, context) => {
  const template = context.buildOptions?.index ?? context.options?.index;

  // Remove the current html plugin added by NX
  let idx = config.plugins.findIndex((plugin) => plugin.constructor.name === 'IndexHtmlWebpackPlugin');
  config.plugins.splice(idx, 1);

  // Push our own version with ejs template syntax enabled
  config.plugins.push(new HtmlWebpackPlugin({ template: path.join(process.cwd(), template) }));

  return config;
};
  1. Configure your build target to use the extended webpack config:
{
  // ...
  "build": {
    "executor": "@nrwl/web:build",
    "outputs": ["{options.outputPath}"],
    "options": {
      // ...
      "index": "apps/admin/src/index.html", // <- important
      "webpackConfig": "apps/admin/webpack.config.js", // <- important
      "generateIndexHtml": false, // <- important
    },
    // ...
  },
}

With this you can use ejs template stuff in your index.html file:

<% if (process.env.NODE_ENV === "production" && process.env.NX_SEGMENT_KEY) { %>
  <script>
    analytics.load(<%= JSON.stringify(process.env.NX_SEGMENT_KEY) %>);
  </script>
<% } %>
1reaction
neilsoultcommented, Apr 28, 2022

Thank you for investigating this @jaysoo!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Environment Variables - webpack
The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be...
Read more >
How to read system environment variable in index.html using ...
Have you tried html-webpack-plugin? It's worked for me adding script paths. From the docs:
Read more >
Create React App: using environment variables in index.html ...
I just tried with an (almost) new CRA setup and it works. <head> <title>React App</title> <script type="text/javascript"> console.log("%REACT_APP_TEST%") ...
Read more >
Adding Custom Environment Variables | Create React App
Your project can consume variables declared in your environment as if they were declared locally in your JS files.
Read more >
Inserting variables into HTML and JavaScript with Webpack
Webpack has been growing in popularity as a way for developers to manage their build process. Webpack is a module bundler that allows...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found