reactjsnode.jsvite.env

Vite restarting server


I can't create .ENV file and run vite project i got infinite loop

here is my vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import dotenv from 'dotenv'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  define:{
    'process.env.VITE_KEY':JSON.stringify(process.env.VITE_KEY)
  }
})
1:52:04 PM [vite] .env changed, restarting server...
X [ERROR] The build was canceled

but if i delete .ENV file i can run my project

I try to create new project but it not work


Solution

  • I reckon that the reason your server was restarting was due to a crash, because process.env.VITE_KEY was undefined and, I guess, vite doesn't accept undefined values:

    define:{
      'process.env.VITE_KEY':undefined
    }
    

    By doing import dotenv from 'dotenv', you're not actually injecting the values from your .env file (docs here).

    What you need to do is:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import 'dotenv/config'
    // or you can do this:
    // import { config } from 'dotenv'
    // config({ path: '.env' })
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react()],
      define:{
        'process.env.VITE_KEY':JSON.stringify(process.env.VITE_KEY)
      }
    })