pdfjs 에러

이윤희·2025년 3월 8일

React/Next 일기

목록 보기
52/52

겨우 빌드 성공했더니만 pdf js 가 api 버전이 안맞는다고? 에러가 뜬다

브라우저 콘솔

hook.js:608 zdetails: "Error: The API version \"3.11.174\" does not match the Worker version \"3.4.120\"."message: "The API version \"3.11.174\" does not match the Worker version \"3.4.120\"."name: "UnknownErrorException"stack: "Error\n at https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:1:6775\n at Object.defineProperty.value (https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:1:6801)\n at w_pdfjs_require (https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:3:101073)\n at https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:3:105647\n at https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:3:105876\n at https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:3:105907\n at https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:1:249\n at 3194 (https://translation-app-lyart.vercel.app/_next/static/chunks/7a49ec60-6be91aea13ff5ef0.js:1:253)\n at d (https://translation-app-lyart.vercel.app/_next/static/chunks/webpack-158cda30e348b9d8.js:1:151)\n at 7170 (https://translation-app-lyart.vercel.app/_next/static/chunks/app/page-6b7601abec51c949.js:1:386)"[[Prototype]]: Error
overrideMethod @ hook.js:608Understand this errorAI

GPT

🚨 PDF 처리 중 오류 해결 방법

🔍 문제 요약:

  • 에러 메시지:
    Error: The API version "3.11.174" does not match the Worker version "3.4.120".
    • PDF.js의 API 버전(3.11.174)과 Worker 버전(3.4.120)이 일치하지 않음
    • 브라우저 환경에서는 PDF.js Worker(웹 워커)별도로 로드되어야 하는데, 현재 설정이 맞지 않음

해결 방법

1️⃣ PDF.js의 버전을 맞추기

현재 PDF.js의 라이브러리 버전Worker 버전이 다릅니다.
👉 최신 버전으로 통일해야 합니다.

📌 package.json에서 pdfjs-dist 버전 확인

"dependencies": {
  "pdfjs-dist": "^3.4.120"
}

⚠️ 이제 pdfjs-dist의 최신 버전(3.11.174)으로 업데이트하세요.

📌 📌 해결 방법 1: 최신 버전 설치

npm install pdfjs-dist@latest

설치가 끝난 후, package.json에서 pdfjs-dist의 버전이 최신인지 확인하세요.


2️⃣ workerSrc 설정 확인 (📌 핵심 문제)

현재 workerSrc 설정이 고정된 버전(3.4.120)을 사용하고 있습니다.
🚀 CDN이 아닌 pdfjs-dist에서 직접 불러오도록 수정하세요.

📌 📌 기존 코드 (고정된 버전)

// lib/pdfProcessor.ts
import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";

GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js`;

⚠️ 이 부분을 수정해야 합니다.

📌 📌 해결 방법 2: pdfjs-dist 내부의 워커 사용

import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.min.js";

// ✅ PDF.js의 Worker를 직접 설정
if (typeof window !== "undefined") {
  GlobalWorkerOptions.workerSrc = URL.createObjectURL(
    new Blob([pdfjsWorker], { type: "application/javascript" })
  );
}

✨ 이렇게 수정하면 버전 충돌 없이 PDF.js가 정상적으로 작동합니다.


🔥 최종 정리 (해야 할 일)

1️⃣ pdfjs-dist 최신 버전으로 업데이트

npm install pdfjs-dist@latest

2️⃣ workerSrc 설정을 pdfjs-dist 내부에서 가져오도록 변경
3️⃣ 다시 빌드 및 배포

rm -rf .next node_modules package-lock.json
npm install
npm run build
npm run dev

4️⃣ Vercel에 다시 배포

vercel --prod

이제 다시 테스트해 보세요! 🚀🔥

근데 이전에 내가 pdf js worker 를 설정할때도 이미 w 뺑이 친 결과로 저렇게해서 겨우 된거였고(아마 변수로 불러오는 데 문제가 있었던 듯)
얘가 하라는대로 하니까 계속 안돼서
그냥 내가 하던 대로 수동으로 버전 집어넣었더니 빌드 됨.

GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.js`;

근데 이러고 나니까 배포버전에서 pdf 처리가 제대로 안 되는 문제가 발생 ㅡㅡ

📌 저장된 고유명사 목록: Array(0)
9b0008ae-89e2daaa9c8dd0b6.js:1 Warning: Setting up fake worker.
pdf.worker.min.js:1 
            
            
           Failed to load resource: the server responded with a status of 404 ()Understand this errorAI
hook.js:608 Error: Setting up fake worker failed: "Failed to fetch dynamically imported module: https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.js".
    at 9b0008ae-89e2daaa9c8dd0b6.js:2:173970
overrideMethod @ hook.js:608Understand this errorAI

"import pdfjsWorker from "pdfjs-dist/build/pdf.worker.min.mjs";" 를 하라는데 이걸 하면 에러가 뜬다. (Cannot find module 'pdfjs-dist/build/pdf.worker.min.mjs' or its corresponding type declarations.ts(2307))

GPT

📌 pdf.worker.min.mjs 모듈을 찾을 수 없다는 오류 해결 방법

🚨 오류 원인:

  • "pdfjs-dist/build/pdf.worker.min.mjs" 파일이 Next.js 빌드 과정에서 번들링되지 않음.
  • Next.js는 기본적으로 .mjs 모듈을 번들에서 제외하는 경우가 있음.
  • 따라서 Next.js가 이 파일을 올바르게 찾고 번들링할 수 있도록 설정을 추가해야 함.

✅ 해결 방법

🔹 1️⃣ next.config.js 수정

먼저, next.config.js웹팩 설정을 추가하여 pdf.worker.min.mjs 파일을 번들링하도록 만듭니다.

📌 next.config.js 수정 (또는 생성)

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.module.rules.push({
      test: /pdf\.worker\.min\.mjs$/, // ✅ pdf.worker.min.mjs를 처리하는 규칙 추가
      type: "asset/resource", // ✅ 번들링 가능하도록 설정
    });

    return config;
  },
};

module.exports = nextConfig;

➡️ 이렇게 하면 pdf.worker.min.mjs가 번들에 포함됩니다.


🔹 2️⃣ lib/pdfProcessor.ts 수정

이제 pdfjsWorker를 직접 불러와서 사용합니다.

📌 lib/pdfProcessor.ts 수정

import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.min.mjs"; // ✅ pdf.worker.min.mjs를 직접 가져오기

// ✅ Web Worker 경로를 패키지 내부에서 직접 설정
GlobalWorkerOptions.workerSrc = pdfjsWorker;

➡️ 이제 Next.js가 pdf.worker.min.mjs번들링하면서 Web Worker가 정상적으로 로드됩니다.

   Creating an optimized production build ...
Failed to compile.

./lib/pdfProcessor.ts
Module not found: Can't resolve 'pdfjs-dist/build/pdf.worker.min.mjs'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./components/PdfUploader.tsx
./app/page.tsx


> Build failed because of webpack errors

아오 ㅡㅡ
전에도 해봤는데 저렇게 하니까 빌드가 안된다고
이 바보야~~~
그래서 결국 다시 수동으로 CDN 설정했다.;;;

import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";

// Web Worker 경로를 고정된 버전으로 직접 설정
GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js`;
   Creating an optimized production build ...
 ✓ Compiled successfully
 ✓ Linting and checking validity of types
 ✓ Collecting page data
 ✓ Generating static pages (6/6)
 ✓ Collecting build traces
 ✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ƒ /                                    424 kB          512 kB
├ ƒ /_not-found                          873 B          88.1 kB
├ ƒ /api/process-text                    0 B                0 B
├ ƒ /api/translate                       0 B                0 B
└ ƒ /api/upload                          0 B                0 B
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-142459c602d8a778.js       31.6 kB
  ├ chunks/fd9d1056-87da80e0c187477b.js  53.6 kB
  └ other shared chunks (total)          2.02 kB


ƒ  (Dynamic)  server-rendered on demand

그러니깐 빌드 된다 ㅡㅡ
이제 PDF 업로드 제대로 됨!!!

0개의 댓글