document is not defined

xohxe (김소혜)· October 19, 2023
문제 상황
'document is not defined'
지난번 scrollTop기능과 window 창 크기 변경에 따른 이벤트를 구현하다가 해당 오류를 겪었는데, 이번에 ToC 기능을 구현하다가 "document is not defined" 빌드 오류를 겪었다.
찾아보니 gatsby JS에서 "document is not defined" 오류는 주로 SSR(Server-Side Rendering) 때문에 발생한다. Gatsby JS는 사이트를 빌드할 때 Node.js 환경에서 사전에 페이지를 렌더링하는데, 이 때 window, document 와 같은 브라우저 전역 객체는 사용할 수 없다.
그래서 로컬에서는 잘 작동하지만, 만약 코드나 사용 중인 플러그인, 라이브러리가 빌드 시에 document나 window 객체를 참조하려고 하면 위와 같은 오류가 발생한다.
해결방법
코드로 보면 아래 코드를 document, window 변수를 사용한 함수에 추가해주면 된다.
if (typeof window === "undefined" || !window.document) {
return;
}
if (!document.body) return 0;참고문서
이전 게시물
알고리즘 풀 때 Xcode 셋팅방법