nx icon indicating copy to clipboard operation
nx copied to clipboard

With react and vite, the .env aren't used if they are in the root

Open hanspoo opened this issue 1 year ago • 3 comments

Current Behavior

If i put an .env file in the root of the project and run dev or prod mode, the variables aren't used. It is necessary to put the file in the application folder.

Expected Behavior

It should work in the root of the project, and sub folder of course with the precedence that appears in the documentation.

GitHub Repo

https://github.com/hanspoo/vite-env-react-demo

Steps to Reproduce

  1. create a workspace integrated with a sole react app.
  2. create env file in root with a variable VITE_XXX
  3. show the variable in the component
  4. serve the react app

to fix

move the env file to the app folder

Nx Report

Node   : 14.21.3
   OS     : linux x64
   npm    : 6.14.18
   Hasher : Native
   
   nx (global)        : 16.1.4
   nx                 : 16.3.0
   @nx/js             : 16.3.0
   @nx/linter         : 16.3.0
   @nx/workspace      : 16.3.0
   @nx/cypress        : 16.3.0
   @nx/devkit         : 16.3.0
   @nx/eslint-plugin  : 16.3.0
   @nx/react          : 16.3.0
   @nrwl/tao          : 16.3.0
   @nx/vite           : 16.3.0
   @nx/web            : 16.3.0
   typescript         : 5.0.4

Failure Logs

No response

Operating System

  • [ ] macOS
  • [X] Linux
  • [ ] Windows
  • [ ] Other (Please specify)

Additional Information

No response

hanspoo avatar Jun 01 '23 13:06 hanspoo

I think there is a plugin for vite missing, which has to load the .env files according to the behavior in nx. Otherwise you can also not use the test runners of your development environments.

floratmin avatar Nov 03 '23 20:11 floratmin

I had this issue when I wanted to run tests directly from the development environment. It worked by loading the environment variables in vite.config.ts:

import {loadEnv} from 'vite';

export default defineConfig({
  ...
  test: {
    ...
    env: {
      ...loadEnv('test', <workspaceDir>, ''),
      ...loadEnv('test', <projectDir>, ''),
    },
  },
});

floratmin avatar Nov 05 '23 14:11 floratmin

This issue has been automatically marked as stale because it hasn't had any recent activity. It will be closed in 14 days if no further activity occurs. If we missed this issue please reply to keep it active. Thanks for being a part of the Nx community! 🙏

github-actions[bot] avatar May 04 '24 00:05 github-actions[bot]

Hi @hanspoo , this issue is fixed in latest Nx, as seen here: https://github.com/jaysoo/issue-17356

Vite itself will only support variables with VITE_ prefix, and we don't want to deviate from that.

jaysoo avatar Jul 25 '24 14:07 jaysoo

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[bot] avatar Aug 27 '24 00:08 github-actions[bot]