Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
wilkinsonjack1993 opened this issue Sep 6, 2021 · 16 comments
Labels

Comments

@wilkinsonjack1993
Copy link

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

@wilkinsonjack1993
Copy link
Author

wilkinsonjack1993 commented Sep 6, 2021

If there is a workaround for this in the meantime, it would be greatly appreciated as it is currently blocking us.
Let me know if you need any more information on this.

@adambrgmn
Copy link

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>
<% } %>

@FrozenPandaz FrozenPandaz added the scope: react Issues related to React support for Nx label Sep 10, 2021
@verymuch
Copy link

@adambrgmn Hi,I had this issue for webpack4 too. But I did not resolve it. Wish to get some ideas from you. Thanks.

First, I changed to use HtmlWebpackPlugin as above. It did not work. Because NX built twice every time. The first time for esm,the built output is right, the variables are replaced. But after the twice build was over, the output is wrong. Like this:

build twice
image

esm result:
image

es5 result:
image

So, I tried some ways to prevent building twice. I tried to set optimization to false.
It worked,just built once,but the output is wrong,variables weren't replaced rightly, the NODE_ENV is wrong.

image

@adambrgmn
Copy link

@verymuch Hm, sorry, but I don't really know what's happening here 🤷‍♂️ We don't do multiple outputs.
Except for editing the html plugin we haven't touched the webpack config at all. And it runs with webpack 5 if I remember correctly.

@Lonli-Lokli
Copy link

Is there any update?

@Lonli-Lokli
Copy link

@FrozenPandaz can you please take a look? We observe same with process.env variables used in tsx for react projects, .env is just ignored for Webpack5 projects.

@rahul-sharma-uipath
Copy link

any update on this? We're also blocked on this

@neilsoult
Copy link

add another blocked dev to the list

@neilsoult
Copy link

Also I don't think this is limited to react, I am using angular and environmental variables are not working for me either

@jaysoo
Copy link
Member

jaysoo commented Apr 27, 2022

Can someone provide a reproduction of this issue?

I have an example for Nx 13 and Nx 14, and both are working.

Nx 13 - https://github.com/jaysoo/nx-13-env-vars
Nx 14 - https://github.com/jaysoo/nx-14-env-vars

If you are running into issues, please make sure you are on the latest versions (13.10.3 and 14.0.3 as of this writing).

@neilsoult
Copy link

neilsoult commented Apr 27, 2022

@jaysoo
https://github.com/neilsoult/nx-demo
nx serve sample
brand new workspace, using npx create-nx-workspace@latest
just created apps in options
installed @nwrl/angular (npm install --save-dev @nrwl/angular)
generated app (nx g @nrwl/angular:app sample)
added .env file and edited index to roughly approximate your sample.
(my global nx version is nx@13.10.2)
image

@jaysoo
Copy link
Member

jaysoo commented Apr 28, 2022

Hi @neilsoult , thanks for the repro.

The problem right now is that @angular-devkit/build-angular-browser doesn't provide the same environment variable support that our executors provide. Let me pull in some people working on the Angular side of things to see where we want to do here.

@jaysoo
Copy link
Member

jaysoo commented Apr 28, 2022

We decided not to add the same support to Angular for now since we don't control the executor/builder. However, I am updating the guide to include some workarounds.

Preview: https://nx-dev-git-fork-jaysoo-docs-env-vars-nrwl.vercel.app/guides/environment-variables#using-environment-variables-in-angular-applications
PR: #10045

Since it sounds like an Angular-specific issue, I'm going to close this once the docs are updated. If you want the same support for Angular, please open a new enhancement issue and we can consider adding it.

@jaysoo
Copy link
Member

jaysoo commented Apr 28, 2022

The guide is updated now: https://nx.dev/guides/environment-variables

Closing this as the React/Web setup is working, and the guide above has some workaround for Angular for those interested.

Again, open a new issue if you want to add similar support to Angular out of the box.

@jaysoo jaysoo closed this as completed Apr 28, 2022
@neilsoult
Copy link

Thank you for investigating this @jaysoo!

@github-actions
Copy link

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 22, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

8 participants