Octavian
Octavian

Reputation: 33

How do I use the .env files config from Webpack to Vite?

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.

Upvotes: 0

Views: 1629

Answers (1)

Ahmed Sbai
Ahmed Sbai

Reputation: 16169

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())
  ...
})

Upvotes: 0

Related Questions