>  기사  >  웹 프론트엔드  >  Fixing vite error for reactjs - global is not defined and process is not defined

Fixing vite error for reactjs - global is not defined and process is not defined

DDD
DDD원래의
2024-09-19 00:57:32134검색

Fixing vite error for reactjs - global is not defined and process is not defined

In a scenario where you are running a vite app with reactjs template for a project and trying to fetch the environment variable from .env file. As the popular way to fetch the environment variables from .env is to use process.env.SOMETHING for the variable as:

SOMETHING=SECRETSAUCE

At this point the vite.config.ts would look like:

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

But fetching variable does not work right away in vite, and there are lots of way to solve the issue. I tried most of them and I felt to stick to the simple and straight forward way.

Probably with above definition and default fetching logic with process.env.*, you would have got error Uncaught ReferenceError: global is not defined.

I find lots of references in stackoverflow and I get confused.

The fix for error is to define global in the config as below.

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  define: {
    global: {},
  },
})

Now, this would probably lead to another more common error Uncaught ReferenceError: process is not defined.

Again, there are many solutions on web and some are outdated. I find the most relevant and easy to implement is to import loadEnv from vite library and build the custom logic as below.

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

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    define: {
      global: {},
      'process.env': env
    },
    plugins: [react()],
  }
})

And the magic happens right away!!

Also to mention, we need not use the dotenv dependency as environment variable fetching in code with process.env.* works well without it.

Happy coding!

위 내용은 Fixing vite error for reactjs - global is not defined and process is not defined의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.