react-pdf: Can't resolve 'canvas' in '(...)/node_modules/pdfjs-dist/build'

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 When building my Gatsby app, I get a module not found error: Error: Can't resolve 'canvas' in '(...)/node_modules/pdfjs-dist/build'

This is likely the same issue as #799 , however, that issue was closed and the issue and solution were Next.js-specific. I’m encountering this issue in Gatsby (v3).

Steps to reproduce

Steps to reproduce the behavior:

  1. Create a Gatsby App
  2. Install react-pdf
  3. Import react-pdf on a page and render a document.
  4. run gatsby build

Expected behavior

What you expected to happen? The app to build.

Additional information I was able to get around this by locking my react-pdf version at 5.2 as suggested in this comment from the #799 issue, however, this should not be a long-term solution. I encountered this error in version 5.4.1.

Environment

  • Browser (if applicable) [e.g. Chrome 57, Firefox 59]: N/A
  • React-PDF version [e.g. 3.0.4]: 5.4.1
  • React version [e.g. 16.3.0]: 17.0.2
  • Webpack version (if applicable) [e.g. 4.16.2]: 4.44.2

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 3
  • Comments: 16 (6 by maintainers)

Most upvoted comments

webpack(config, { isServer }) {
      // https://github.com/wojtekmaj/react-pdf/issues/799
      // https://github.com/mozilla/pdf.js/issues/13373
      if (isServer) {
        config.resolve.alias.canvas = false;
      }

      return config;
    },

That is how I solved the issue, canvas usage in the SSR should be avoided since it wouldn’t make much sense

Leaving this here if people are integrating react-pdf with something like docusaurus. I took @yordis’s solution and added a docusaurus plugin for react-pdf: https://github.com/syed-ahmed/docusaurus-plugin-react-pdf 😃. I was facing the problem mentioned in this issue before making this plugin. Since docusaurus exposes configuration of webpack using plugins, it made sense to encapsulate react-pdf as a plugin. The current plugin doesn’t expose all the configuration that react-pdf provides and I don’t have any plans right now to extend this, but contributions are welcome. My rendered pdfs look great, so thanks react-pdf authors!

image

I had the same error while using react-pdf on Gatsby, and I fixed it using that solution to an issue on another package: https://github.com/react-pdf-viewer/react-pdf-viewer/issues/497#issuecomment-812905172

This doesn’t seem specific to Gatsby as I’m also getting the same error with Next.js 11.1.2 no matter how I try to import react-pdf (normal, dynamic, and dynamic w/ ssr disabled).