Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require is not defined - pdf is not rendered on Chrome #782

Closed
4 tasks done
tomaszzmudzinski opened this issue May 12, 2021 · 52 comments
Closed
4 tasks done

require is not defined - pdf is not rendered on Chrome #782

tomaszzmudzinski opened this issue May 12, 2021 · 52 comments
Assignees
Labels
bug Something isn't working help wanted Extra attention is needed

Comments

@tomaszzmudzinski
Copy link

tomaszzmudzinski commented May 12, 2021

Before you start - checklist

  • I followed instructions in documentation written for my React-PDF version
  • I have checked if this bug is not already reported
  • I have checked if an issue is not listed in Known issues
  • If I have a problem with PDF rendering, I checked if my PDF renders properly in Mozilla Firefox

Description

After updating the react-pdf library from 5.2.0 to 5.3.0 pdf stopped being rendered on Chrome. All I can see is: Failed to load PDF file.

On the google chrome console I can find:

Uncaught ReferenceError: require is not defined

Zrzut ekranu 2021-05-12 o 11 21 46

Zrzut ekranu 2021-05-12 o 11 22 07

This problem exists only on google chrome because everything works without any problem on Firefox 88.0.

Environment

  • Browser: Chrome 90
  • React-PDF version: 5.3.0
  • React version: 17.0.2
  • Webpack version: 4.44.2
@jorge-uproar
Copy link

I have the same issue but my react-pdf version is 5.2.0 I just remember updating npm to the lts

@abdulrehman1937
Copy link

Same issue working fine in dev but gives error in production. Tested on chrome and edge.

@tomaszzmudzinski
Copy link
Author

Same issue working fine in dev but gives error in production. Tested on chrome and edge.

Exactly! It works in the local environment and the problem exists on production with chrome/edge browsers

@rashadatjou
Copy link

Can confirm we are experiencing the same issue on production ( development works fine ). Currently using yarn 1.22.4 with node 14.5.1 with create react app.

@jorge-uproar
Copy link

I managed to solve this problem in the following way:

  1. Instead of use 'react-pdf/dist/esm/entry.parcel' or 'react-pdf/dist/umd/entry.parcel' just use only the direct 'react-pdf'
  2. Since you are going to use this direct reference so you need to copy 'pdfjs-dist/build/pdf.worker.js' to your public folder
  3. Then you'll have to import it in this way: pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';

Screen Shot 2021-05-17 at 9 17 50 AM

I used to use the Document from 'react-pdf/dist/esm/entry.parcel' but since I started having the required error I had to switch to that other way

@andreareginato
Copy link

I managed to solve this problem in the following way:

  1. Instead of use 'react-pdf/dist/esm/entry.parcel' or 'react-pdf/dist/umd/entry.parcel' just use only the direct 'react-pdf'
  2. Since you are going to use this direct reference so you need to copy 'pdfjs-dist/build/pdf.worker.js' to your public folder
  3. Then you'll have to import it in this way: pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';

I've been following the suggested steps but i still get the error Uncaught ReferenceError: require is not defined in production (in development it works correctly). Before the error I also see in console Warning: Setting up fake worker.

import { Document, Page, pdfjs } from 'react-pdf';
/** /pdf.worker.min.js accessible form public at /pdf.worker.min.js */
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';

Any other suggestion to overcome the current issue?

@rashadatjou
Copy link

rashadatjou commented May 20, 2021

Hi @andreareginato, the only way I know that is going to work is by going to your package.json file and setting the version of react-pdf to 5.2.0 ( directly copied from my package.json file "react-pdf": "5.2.0" ). After explicitly setting the version do a npm i or yarn install so that the new changes take effect.

Side note:
Make sure to remove the symbol ^ before the version number of the package as this will cause the package manager npm or yarn to always install the latest version of the package which is the 5.3.0 that has this bug.

Will work ✅:
"react-pdf": "5.2.0"

Won't work 🛑:
"react-pdf": "^5.2.0"

@slugmandrew

This comment has been minimized.

@andreareginato

This comment has been minimized.

@starloveit

This comment has been minimized.

@wojtekmaj wojtekmaj added the bug Something isn't working label Jun 4, 2021
@wojtekmaj wojtekmaj self-assigned this Jun 4, 2021
@sm3sher
Copy link

sm3sher commented Jul 9, 2021

As of for now "react-pdf": "5.3.2" still has the same issue. Is there any progress on this, I don't want to miss out on newer versions of this great library.

@tomaszzmudzinski
Copy link
Author

@wojtekmaj any progress on this? :)

@wojtekmaj
Copy link
Owner

Nope, still no idea what the fix could look like. I'm also not getting it in any of my personal projects. These are based on Webpack 5 though so maybe the issue is affecting Webpack 4 only?

@uwemneku
Copy link

Hi @andreareginato, the only way I know that is going to work is by going to your package.json file and setting the version of react-pdf to 5.2.0 ( directly copied from my package.json file "react-pdf": "5.2.0" ). After explicitly setting the version do a npm i or yarn install so that the new changes take effect.

Side note:
Make sure to remove the symbol ^ before the version number of the package as this will cause the package manager npm or yarn to always install the latest version of the package which is the 5.3.0 that has this bug.

Will work ✅:
"react-pdf": "5.2.0"

Won't work 🛑:
"react-pdf": "^5.2.0"

This solution worked for me

@LiHaoGit
Copy link

import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack'

const url = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`
pdfjs.GlobalWorkerOptions.workerSrc = url

work for me

@wojtekmaj wojtekmaj added the help wanted Extra attention is needed label Jul 27, 2021
@wojtekmaj wojtekmaj changed the title Require is not defined - pdf is not rendered on chrome require is not defined - pdf is not rendered on Chrome Jul 29, 2021
@PCOffline
Copy link

PCOffline commented Aug 11, 2021

@LiHaoGit's solution worked for me.
I'm curious, what makes it run locally but not on the dev/prod environment though? Does localhost have something to do with this?

@wojtekmaj
Copy link
Owner

I've set up sample repos on my server here:

https://projects.wojtekmaj.pl/react-pdf/webpack4/
https://projects.wojtekmaj.pl/react-pdf/webpack5/

URLs are self-explanatory I think. Looks like both built and dev code works for me with default entry. I'm using the latest React-PDF version here. Anyone can reproduce this issue on the pages above?

@PCOffline
Copy link

PCOffline commented Aug 16, 2021

Can you provide the source code? Also, how do you run these pages?

@komret
Copy link

komret commented Aug 17, 2021

I have the same problem using react-pdf 5.3.2, react 17.0.2 and create-react-app 4.0.3 (i.e. webapack 4). When I import Document and Page from react-pdf/dist/esm/entry.webpack (or react-pdf/dist/umd/entry.webpack) and build the project, it outputs an extra file (plus a license file) into the build directory which causes the error. It does not appear in development because the build files are not used when running from webpack devServer. I had the error not only in Chrome but also Firefox.

The solution suggested by @jorge-uproar or import from CDN works for me.

@PandaPandaPanda
Copy link

This bug costed me half a day. Thank you for saving me out of my misery.
Denpex's solution works

@peterpeterparker
Copy link

peterpeterparker commented Sep 30, 2021

v5.4.0 that has been released 3 days ago seems to have solve the issue for me.

Today I have also upgraded (clean install of the dependencies) to Node v16 and npm v7, but do think the above release fixed it. In any case, build the app and deployed it on staging and did not had the error anymore.

Note: I use the esm version

import {Document, Page} from 'react-pdf/dist/esm/entry.webpack';

Thanks a lot @wojtekmaj and @njleonzhang !!!

@sm3sher
Copy link

sm3sher commented Sep 30, 2021

As of for now "react-pdf": "5.3.2" still has the same issue. Is there any progress on this, I don't want to miss out on newer versions of this great library.

This seems to be indeed fixed in v5.4.0.
@tomaszzmudzinski can you confirm and close this issue?

@Tjeerd
Copy link

Tjeerd commented Nov 1, 2021

New release fixed it for me as well!

@sm3sher
Copy link

sm3sher commented Nov 22, 2022

Still happening with v6.2.0

@wojtekmaj
Copy link
Owner

Is there a reproducible example you can share @sm3sher?

@mikegoatly
Copy link

@sm3sher Are you copying pdf.worker.js to your project's output folder?

After I upgraded to v6 I noticed that I'd completely missed that step when I got started while using v5 and adding it via the CDN option got things working again.

@sm3sher
Copy link

sm3sher commented Dec 6, 2022

I tried the first option and unfortunately it was not working with this solution:

pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';

The CDN option worked out but I have react-apps that run inside a local context without internet access.

@shashankitsoft
Copy link

shashankitsoft commented Dec 7, 2022

@wojtekmaj I am also getting the same error after upgraded from 5.7.2 to latest 6.2.0. I am running React 18.x.

Using import { Document, Page } from "react-pdf/dist/esm/entry.webpack5";

Its working on my localhost but on production it gives error:
Warning: Setting up fake worker.
pdf.worker.fca3091210ba0a730cc1.js:2 Uncaught ReferenceError: require is not defined

With 5.7.2 it was working fine. Any recommended solution or I should revert to old version?

@shashankitsoft
Copy link

shashankitsoft commented Dec 7, 2022

For now @LiHaoGit 's CDN solution worked for me, also with webpack5 import.

@entrust-ajit
Copy link

For now @LiHaoGit 's CDN solution worked for me, also with webpack5 import.

I am also using react-pdf version "^6.2.0" and running React "^18.1.0". I tried to implement @LiHaoGit 's CDN solution, but it didnt work for me. It is not throwing any error on the console as well. Below is my code. Any help is highly appreciated.

import React, { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack5';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import './PdfViewerTemplate.less';
const url = //cdn.jsdelivr.net/npm/pdfjs-dist@3.1.81/build/pdf.worker.min.js
pdfjs.GlobalWorkerOptions.workerSrc = url

const options = {
cMapUrl: 'cmaps/',
cMapPacked: true,
standardFontDataUrl: 'standard_fonts/',
};

export const PdfViewerTemplate = ({props}) => {
const [pdfFileData, setPdfFileData] = useState(_base64ToArrayBuffer(props));
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
const [renderNavButtons, setRenderNavButtons] = useState(false);

function _base64ToArrayBuffer(base64) {
  var binary_string = window.atob(base64);
  var len = binary_string.length;
  var bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}

const onSuccess = () => {
  setPageNumber(1);
  setRenderNavButtons(true);
}

const changePage = (offset) => {
  setPageNumber(prevPageNumber => prevPageNumber + offset);
}

const previousPage = () => { changePage(-1); }

const nextPage = () => { changePage(+1); }

return (
  <div className="Pdfview">
    <div className="Pdfview__container">
    <div className="Pdfview__container__document">
    <Document file={{data: pdfFileData}} 
              onLoadSuccess={({ numPages }) => {
                setNumPages(numPages);
                setRenderNavButtons(true);
                onSuccess;
              }} 
              options={options}>
    <Page pageNumber={pageNumber} width={400} height={500} scale={1.0}/>
    {renderNavButtons &&
    <div>
      <button
        className={pageNumber <= 1 ? 'disabled-form-button' : 'form-button'}
        onClick={previousPage}
      >
        Previous
      </button>
      <button
        className={pageNumber === numPages ? 'disabled-form-button' : 'form-button'}
        onClick={nextPage}
      >
        Next
      </button>
    </div>}
    </Document>
    </div>
    </div>
  </div>

);
}

@nocive
Copy link

nocive commented Jan 9, 2023

Experiencing the same error with react-pdf 6.2.1 and CRA (webpack5).
None of the workarounds discussed here worked.

@rashadatjou
Copy link

Does this issue need help fixing? I would like to give it a try? @andreareginato @wojtekmaj

@wojtekmaj
Copy link
Owner

@rashadatjou Yes, if it's still reproducible then yes. We have a bunch of sample repositories in here to test React-PDF with CRA5, Webpack 4, Webpack 5 and others, but it seems it's not enough.

@nocive
Copy link

nocive commented Jan 16, 2023

should this ticket be reopened then?

@carlossalasamper
Copy link

import { Document, Page } from "react-pdf/dist/esm/entry.webpack5";
In version 6.2.2 getting the same error

dpittman7 added a commit to dpittman7/pittman_react that referenced this issue Jan 26, 2023
@zwarrell
Copy link

zwarrell commented Jan 29, 2023

I am running react-pdf 6.2.2 and had this error. I got everything working with the following.
import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.2.16.105.js'

I downloaded the pdf.worker.min.js from this link (https://cdn.jsdelivr.net/npm/pdfjs-dist@2.16.105/build/pdf.worker.min.js) and put it in my public directory named as (pdf.worker.min.2.16.105.js) so I am not dependent on a CDN.

Hope this helps someone else!

This library is awesome!

@abacaj
Copy link

abacaj commented Feb 3, 2023

Was trying to fix this issue, then decided I should see if someone else had it.

Turns out from all of the folks here having the same issue - it's extremely hard to get a pdf document loaded with a single library on the browser using create-react-app.

Only solution that worked for me is:

import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack';
const url = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
pdfjs.GlobalWorkerOptions.workerSrc = url;

On react 17, react-scripts 4.0.3

@dbouclier
Copy link

dbouclier commented Feb 10, 2023

Same issue for me,

work around work with both https://cdnjs.cloudflare.com/ajax/libs/pdf.js/{pdfjs.version}/pdf.worker.min.js
or cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js;

but we expect the library should come with all the dependencies, @wojtekmaj so I guess this issue is still open, no?

@wojtekmaj
Copy link
Owner

@dbouclier You're correct, but this issue is not reproducible in any of our existing samples, so I'll need one to look into this matter closely.

@dbouclier
Copy link

@wojtekmaj I got this issue only with production build, everything was working locally.

no sure the samples are using the same dependencies as me
(basically yarn + typescript + CRA5 + react 18 + webpack5)

details :

 "dependencies": {
     "react": "^18.2.0",
     "react-pdf": "^6.2.2",
 },

 "devDependencies": {
     "@types/node": "^16.11.65",
     "@types/react": "^18.0.26",
     "@types/react-pdf": "^6.2.0",
     "react-scripts": "^5.0.1",
     "typescript": "^4.9.4",
     "webpack": "^5.75.0"
 },

 "packageManager": "yarn@3.2.3"

How I can help ? do you need more details ?

@allicanseenow
Copy link

Yeah. I've found out that this issue doesn't happen with the dev env. But if you build it and run the prod build on localhost, you can see the issue if you don't set pdfjs.GlobalWorkerOptions.workerSrc

@jack-bgl
Copy link

Seem issue with my project, "react-pdf": "^5.7.1"
Should open this again?

@rashadatjou
Copy link

rashadatjou commented Mar 1, 2023

This bug only happens with create-react apps (I suspect it is something with how babel works with create-react-app). I was able to reproduce the bug on the sample create-react-app-5. I have made a fork to fix the sample create-react-app-5 as it is broken currently and does not work: #1358.

@wojtekmaj You can go to my fork https://github.com/rashadatjou/react-pdf and when you build the create-react-app-5 sample with yarn build and run it locally e.g. serve -s build you will get the bug that is happening above. I do not know what is causing this though :D

@nocive
Copy link

nocive commented Mar 3, 2023

please reopen the issue!

@rashadatjou
Copy link

rashadatjou commented Mar 3, 2023

@nocive this might help

From the README:

Standard instructions will also work with Create React App. Please note that in Create React App, you can copy pdf.worker.js file from pdfjs-dist/build to public directory in order for it to be copied to your project's output folder at build time.

Copy over node_modules/pdfjs-dist/build/pdf.worker.js to public/ when building for production.

@hsjakobsen
Copy link

I managed to solve this issue for both development and production

My setup:
Browser: Chrome 110 and Firefox 110
React-PDF version: 6.2.0
React version: 18.2.0
Webpack version: 5.64.4 (bundled with react-scripts).
React-scripts: 5.0.1

import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
pdfjs.GlobalWorkerOptions.workerSrc = './pdf.worker.min.2.16.105.js';

So what I did was to follow the advice of zwarrell and download the pdf.worker.min.js and rename it. See the comment link below:
#782 (comment)

I put it in my public folder and I put it inside the src to be able to load it while developing.

In order to have my PDF render properly I imported the following 2 styling files:
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';

@Jimlala
Copy link

Jimlala commented Apr 28, 2023

I am running react-pdf 6.2.2 and had this error. I got everything working with the following. import { Document, Page, pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.2.16.105.js'

I downloaded the pdf.worker.min.js from this link (https://cdn.jsdelivr.net/npm/pdfjs-dist@2.16.105/build/pdf.worker.min.js) and put it in my public directory named as (pdf.worker.min.2.16.105.js) so I am not dependent on a CDN.

Hope this helps someone else!

This library is awesome!

Worked for me too. Thanks.

@codeWriter6
Copy link

My setup:
reacct-pdf: 6.2.2,
webpack: 4
react: 17.0.2,
Load worker from CDN solve this error. But we have strict CSP policy and load work worker from CDN is not allowed. The import worker configuration posted in the doc does not work.
Only solution that worked for me is:

import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

@wojtekmaj I suggest to add this to the doc.

@moonkid196
Copy link

This final approach seemed to get the file into the build for me, but one tweak: didn't work for my typescript app, due to no declarations file. But simply importing the file was sufficient, then left the existing worker config from the examples:

import "pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.js',
  import.meta.url,
).toString();

@tarikt-hybird
Copy link

tarikt-hybird commented Sep 27, 2023

If anyone is still facing this issue I have followed this approach: #852 (comment)

By using approach from @codeWriter6 above I resolved the issue in production but faced an annoying issue in the localhost: "Uncaught runtime errors: Worker was terminated". So to fix that as well I followed the link above.

My setup:

"react": "^16.8.6",
"react-pdf": "^7.4.0"

The fix from @dmr07 from the link above that worked for me:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`; 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests