Vite를 이용해 프로젝트를 빌드하고 배포한 후, 실행해보니 ReferenceError가 발생했다.
Uncaught ReferenceError: Cannot access '_u' before initialization
at vendor-C-CSqHJx.js:9:18050
개발자 도구의 Sources 탭에서 vendor-C-CSqHJx.js:9:18050 위치로 이동해 오류를 확인해보니..
useInsertionEffect에서 에러가 발생하고 있었다.
일단 ReferenceError 에러란게 보통 let 또는 const 로 선언한 변수의 코드가 실행되기 전에 해당 변수를 사용했을 때 생기는 오류라고 알고있었다. 그래서 이 에러도 그런 비슷한게 아닐까.. 하고 추측하며 useInsertionEffect 참조 에러에 대해 열심히 찾아봤다!
첫 번째 해결 시도: 버전 다운그레이드
Material ui export 'useInsertionEffect' (imported as 'useInsertionEffect$1') was not found in 'react' using Appbar component
1: https://i.sstatic.net/Y2Zdo.png**strong text** here i am trying to use Appbar component of material ui but i get this error
stackoverflow.com
에러를 해결하기 위해 처음 시도해본 것은 관련 라이브러리들의 버전을 낮춰보는 방법이다.
1. @emotion/react → 11.7.1 버전으로 다운그레이드
2. @mui/material → 5.4.2, @emotion/react → 11.7.1, @emotion/styled → 11.6.0 버전으로 다운그레이드
3. React → 17로 다운그레이드한 후, 모든 의존성을 해당 버전에 맞게 조정
그러나 이 방법만으로는 문제를 해결할 수 없었다. 😢
두 번째 해결 시도: terser 사용해보기
https://github.com/JedWatson/react-select/issues/5076
error 'useInsertionEffect' · Issue #5076 · JedWatson/react-select
Hi, I've created a project with the same react and emotion versions, and I get this error: `ERROR in ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js 95:25-45 export 'useInsertionEff...
github.com
terser의 compress: { evaluate: false } 옵션을 추가하면 문제가 해결된다는 내용을 발견했다!
이에 따라 vite.config.ts 파일을 수정해 적용해 보았다.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
base: '/',
server: {
port: 3000,
open: true,
proxy: {},
},
build: {
minify: 'terser', // terser로 빌드
commonjsOptions: {
transformMixedEsModules: true,
},
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('react')) return 'react-vendor';
if (id.includes('node_modules')) return 'vendor';
},
},
},
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
evaluate: false, // 이 옵션을 추가해서 문제를 해결함
},
},
},
plugins: [react(), tsconfigPaths()],
});
하지만 이 방법도 실패...
세 번째 해결 시도
😵💫 도저히 해결될 기미가 안 보였다…
버전 다운그레이드도 해보고, 설정도 바꿔보고, 공식 문서도 찾아봤지만 여전히 해결되지 않는 오류…
이대로는 안 되겠다 싶어서 결국 Emotion 라이브러리의 GitHub 페이지 ( Emotion 관련 오류라는 것을 거의 확신했었다 )에 가서
끝이 보이지 않는 이슈들을 뒤지기 시작했다.
비슷한 문제를 겪은 사람을 발견!
수많은 이슈들 사이에서 나와 똑같은 문제를 겪은 개발자의 글을 발견했다!
그도 나처럼 헤매다가 문제를 올렸고, 다행히도 Emotion의 컨트리뷰터인 Andarist가 직접 답변을 달아두었다.
https://github.com/emotion-js/emotion/issues/2649
Can't build a simple CRA app with v11.8.0 · Issue #2649 · emotion-js/emotion
Current behavior: A build of a CRA app with React 17, MUI 5 (thus requiring emotion) fails quickly with: Creating an optimized production build... Failed to compile. Attempted import error: 'useIns...
github.com
Andarist가 제기한 이슈에서 발생한 문제의 원인은 트랜스파일 과정에서 useInsertionEffect가 import 문에서 직접 참조되는 오류가 발생한 것이다.
Andarist가 말한 해결방법은 2가지인데,
해결 방법 1: external에 추가하기
Emotion 라이브러리를 peerDependencies에 추가한다고 해서 번들링 방식이 자동으로 바뀌지는 않는다.
따라서 Vite의 external 옵션을 사용하여 직접 외부 라이브러리로 처리해주면 된다.
해결 방법 2: 번들에 포함시키기
만약 Emotion을 번들에 포함하고 싶다면, peerDependencies에서 제거한 후 직접 의존성으로 추가해야 한다.
그리고 @emotion/use-insertion-effect-with-fallbacks도 함께 설치해야 한다.
내가 선택한 방법
나는 해결 방법 1 (external로 처리)와 해결 방법 2 (의존성 추가)를 동시에 적용하여 문제를 해결했다.
( 한 방법만 해서는 해결되지 않았다.. )
1. Emotion 라이브러리를 번들링에서 제외하여 불필요한 코드가 포함되지 않도록 했고
2. @emotion/use-insertion-effect-with-fallbacks를 설치하여 Vite가 모듈을 올바르게 찾을 수 있도록 했다.
최종 vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
base: '/',
server: {
port: 3000,
open: true,
},
build: {
minify: 'terser',
commonjsOptions: {
transformMixedEsModules: true,
},
rollupOptions: {
external: ['./@emotion/react', './@emotion/styled', './@emotion/use-insertion-effect-with-fallbacks'],
output: {
globals: {
'./@emotion/react': 'emotionReact',
'./@emotion/styled': 'emotionStyled',
'./@emotion/use-insertion-effect-with-fallbacks': 'emotionInsertionEffectFallbacks',
},
},
},
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
evaluate: false,
},
},
},
optimizeDeps: {
exclude: ['@emotion/use-insertion-effect-with-fallbacks'],
},
plugins: [react(), tsconfigPaths()],
});
장장 4시간의 사투 끝에.. 드디어 해결 완료!
'Develop' 카테고리의 다른 글
gpt-error-analyzer 라이브러리 개발기: 실시간 에러 분석 자동화 (0) | 2025.04.08 |
---|---|
디스코드 알림봇 만들기: 반복 메시지, 슬래시 커맨드, 자동 등록까지 (0) | 2025.04.08 |
[ React Native ] Error while updating property 'borderTopLeftRadius' of a view managed by: RCTImageView (0) | 2025.01.08 |
[ CI/CD ] GitHub Actions로 AWS EC2 배포 시 환경변수 적용 문제 해결기 (0) | 2025.01.07 |
[ SpringBoot ] 회원가입 API 설계 고민 (0) | 2025.01.04 |