0

I recently started migrating my app from Create React App to Vite, but I am struggling to understand how to replicate the same .env file setup to Vite.

In CRA, I used CRACO and the following config:

//craco.config.js

const path = require('path')
const webpack = require('webpack')

require('dotenv').config({
  path: path.resolve(__dirname, './.env.' + process.env.APP_ENV),
})

module.exports = {
  webpack: {
    plugins: [
      new webpack.DefinePlugin({
        DEV: process.env.APP_ENV === 'local',
        DOMAIN: JSON.stringify(process.env.API_URL),
      }),
      new webpack.ProvidePlugin({
        React: 'react',
        ReactDom: 'react-dom',
      }),
    ],
  },
}

And I had .env files for the different environments: .env.local, .env.development, .env.stage, .env.production

These files had key value pairs with the variables like API_URL=https://example.com

And in order to access them in my .JSX files I could do so like this:

console.log(DEV, DOMAIN)

I tried the following vite.config.js to replicate the same setup as before:

// vite.config.js


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

export default defineConfig({
  plugins: [
    EnvironmentPlugin({
      DEV: process.env.APP_ENV === 'local',
      DOMAIN: process.env.API_URL,
    }),
    react()
  ],
})

But when trying to run vite, I get the following error:

error when starting dev server:
Error: vite-plugin-environment: the `DOMAIN` environment variable is undefined.
Octavian
  • 33
  • 2
  • 7

1 Answers1

0

Vite does not load .env files by default so you should also import loadEnv from vite module

import { defineConfig, loadEnv } from 'vite'

then load .env file :

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd())
  ...
})
Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
  • I added the loadEnv but didn't quite fix the problem. Here is my config: ``` export default defineConfig(({ command, mode }) => { const env = loadEnv(mode, process.cwd()) return { plugins: [ react(), EnvironmentPlugin({ DEV: env.APP_ENV === 'local', DOMAIN: env.JTI_API, GAA: env.GoogleAccount, GTM: env.GoogleTagManager, GO: env.GoogleOptimize, BlobHost: env.BlobHost, }), ], } }) ``` – Octavian Jan 29 '23 at 09:50