본문 바로가기

개발일지/error

Uncaught ReferenceError: global is not defined at node_modules/buffer/index.js

반응형

"global is not defined"

 

 vite를 이용해 react 프로젝트를 하던 중 aws-sdk를 설치 후 AWS관련 패키지를 이용하려고 했을 때 만났던 오류이다. vite를 이용하지 않고 react프로젝트를 만들었을 시에는 오류가 뜨지 않아 원인을 좀 찾아보았다. 

 

https://stackoverflow.com/questions/72114775/vite-global-is-not-defined

 

Vite 'global is not defined'

I'm creating a project using Vite with vanilla-ts, at one point I had to use the readdir method from the fs-extra package, but it created an error saying process is not defined, some suggested I pl...

stackoverflow.com

문제는 vite가 webpack 처럼 창에 있는 글로벌 필드를 정의하지 않기 때문입니다. 그리고 일부 라이브러리는 webpack이 vite보다 훨씬 오래되었기 때문에 webpack 에 의존합니다.

 

두 가지의 해결 방법이 있었다.

 

 첫 번째로 src폴더 아래에 init.js파일을 하나 만들어 준 후 아래의 코드를 입력해 준다.

window.global ||= window;

그리고 main.tsx에서 가장 상단에서 위의 init.js를 import 해 준다.

import "./init"
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'

 두 번째 해결방법으로는 vite.config.ts에 global 정의를 추가해 준다.

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

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

 

반응형