wojtekmaj/react-pdf

[v6] Module parse failed: Unexpected character '#' when using Create-React-App

sabotag opened this issue Β· 50 comments

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 PDF.js demo

Description

Our team is waiting for a new version of react-pdf with a new build of pdfjs-dist, which has a fix for Hebrew, so for the test, we tried to install the 6th version of react-pdf but after installation we got the following error
Screenshot 2022-08-29 at 14 16 25

Steps to reproduce

install
react-pdf 16 or 17
react-scripts: 3.4.4
implement react-pdf@v6.0.0-beta.3

Expected behavior

Actual behavior

./node_modules/pdfjs-dist/build/pdf.js 1390:17
Module parse failed: Unexpected character '#' (1390:17)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
|         class PDFDocumentLoadingTask {
>           static #docId = 0;
| 
|           constructor() {

Additional information

how can we solve this problem? Thank you

DEMO

Environment

  • Browser (if applicable): chrome
  • React-PDF version: 6
  • React version: 17
  • react-scripts: 3.4.4

Hmmm, tried running 6.0.0-beta.3 with my Create React App 5 sample app and it went without any issues. I suspect react-scripts 3.4.4 might be a bit too old πŸ€”

Same issue here.
As far as I am concerned react-scrits 3.x.x still seems to be pretty common these days and migrating to 4.x branch sometimes is not an option for any reason

Any chances to get some help with this?

Maybe it's possible to update Babel manually? I hope they didn't pin Babel version in CRA?

Hello, I am on react-scripts 4.0.3 and I have the very same problem.

We have tests for CRA 5, CRA 4 might need additional configuration which I haven't discovered yet

This is my code
import React, { useState } from "react";
import { Document, Page } from "react-pdf/dist/esm/entry.webpack";

import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "react-pdf/dist/esm/Page/TextLayer.css";

const PdfPreview = ({ data }) => {
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);

const onDocumentLoadSuccess = ({ numPages }) => {
setNumPages(numPages);
};

const goToPrevPage = () =>
setPageNumber(pageNumber - 1 <= 1 ? 1 : pageNumber - 1);

const goToNextPage = () =>
setPageNumber(pageNumber + 1 >= numPages ? numPages : pageNumber + 1);

return (



Prev
Next


Page {pageNumber} of {numPages}


  <Document file={data.path} onLoadSuccess={onDocumentLoadSuccess}>
    <Page pageNumber={pageNumber} />
  </Document>
</div>

);
};

export default PdfPreview;

Error
image

packages

"react-pdf": "^6.0.3",
"pdfjs-dist": "^3.0.279",

please give a solution

Hi all, #'s meaning is private class member since typescript 3.8 starts support. Please make sure you use the package: @types/react-pdf version 5.0.5. This version of @types/react-pdf supports ts3.6 and ts3.6 don't introduce # as private class member.
Also please don't use version 5.0.9 of @types/react-pdf because it supports both ts3.7 and ts3.8.

I have tested combinations and they work on environment and packages:
@types/react-pdf: 5.0.5 <- This works on ts3.6. It's critical
react-pdf: 5.3.0, 5.3.2. I believe later versions of 5.3.0 in series 5 will worked as 5.3.0.
react-script: 3.4.3
react: 16.13.1
pdfjs-dist: 2.6.347
typescript: 3.7.3
nodejs: 14.19.0

other packages for assist compile:
copy-webpack-plugin: 6.4.1
webpack: 4.42.1
react-app-rewired: 2.1.5

same thing in storybook

"@storybook/react": "^6.5.13",
"react-pdf": "^6.1.1"

ERROR in ./node_modules/pdfjs-dist/build/pdf.js 1413:9
Module parse failed: Unexpected character '#' (1413:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| class PDFDocumentLoadingTask {
>   static #docId = 0;
| 

I also tried to add "@babel/plugin-proposal-class-static-block", but did not work.

Another data point; I'm seeing this with:

"react-scripts": "^4.0.3",
"react": "^16.12.0",
"react-pdf": "^6.2.0",
"typescript": "^4.2.4",
clmz commented

@victors1681
Did you figure out any solution? I have the same issue with storybook.

Did you figure out any solution? I have also this same issue :(

also have same issue
./node_modules/pdfjs-dist/build/pdf.js 1410:17 Module parse failed: Unexpected character '#' (1410:17) File was processed with these loaders: * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. | | class PDFDocumentLoadingTask { > static #docId = 0; | | constructor() {

Had the same issue and found no solution (had to revert to react-pdf version 5.0.0)

I think that this problem is not specific to create-react-app. Most of the tooling will not transform code that comes from node_modules, unless you explicitly ask them to do so. Clearly, private class properties are not supported by all browsers yet so if some project is willing to support older browsers as well they will not be able to include this package easily. I am wondering if it would be possible to have an es5 or perhaps es6 compatible builds distributed along with this package.

Edit: I've just realized that this comment would be more appropriate for https://github.com/mozilla/pdfjs-dist.

Ok, so apparently pdfjs-dist actually ships with builds for legacy browsers, but this needs to be imported differently, e.g.

import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf';

Perhaps it would be more prudent if react-pdf could import those legacy (more compatible) builds instead?

Legacy builds were dropped in #988. One of the main reasons was that this made the code insanely big and this kept crashing people's machines due to out of memory errors.

@wojtekmaj, getting the same error here:

./node_modules/pdfjs-dist/build/pdf.js 1540:17
Module parse failed: Unexpected character '#' (1540:17)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
|         class PDFDocumentLoadingTask {
>           static #docId = 0;
| 
|           constructor() {

    "react-pdf": "^6.2.0",
    "@types/react-pdf": "^6.2.0", // I'm not using typescript in the main project, just added upon previous suggestion.
    "react-scripts": "4.0.0",

Oddly enough it was working until I changed branches and it was totally broken when I switched back.

edit: I tried rolling back to 5.7.2 and still getting the same error, unless 6.2.0 is cached or something weird.

The error goes away when I comment the import statement out:
import { Document, Page, pdfjs } from "react-pdf";

Also, I'm using Chrome: 108.0.5359.98, but that shouldn't make a difference since this fails during the compilation step.

I've had this error on react-pdf above 4.2.0 so if you are desperate to get this implemented in a hurry I would suggest downgrading to 4.2.0.

Currently running on:
react-scripts: 4.0.3

Anyone have any build solutions?

I managed to get react-pdf 6.2.2 to work with deps webpack 4.46.0 and @babel/preset-env 7.20.2

I found using the include property of the babel rule and adding pdfjs-dist after the source built and rendered successfully.
Heres and snip of the webpack config for the rule:

const np = require('path')

module.exports = {
  // ...
  module: {
    // ...
    rules: [
      {
        test: /\.(mjs|jsx|js)$/,
        include: [
          np.resolve('src'),
          // babel-env has all the presets to build pdfjs, just needs to be included
          np.resolve('node_modules/pdfjs-dist/build'),
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              babelrc: false,
              configFile: false,
              presets: [
                '@babel/preset-env',
                // ....
              ],
              plugins: [
                '@babel/plugin-syntax-dynamic-import',
                // ...
              ],
            },
          },
        ],
      },
    ],
  },
}

I hope that helps someone that was also stuck on the Module parse failed: Unexpected character '#' (1413:9) build error

did anyone happen to get react-pdf 6.2.2 working via webpack 4? the recommendation below of @Nubuck didn't help. thanks.

This is still failing...

@evanjmg Update to webpack 5 it should solve this issue.

You Needs to downgrade you package version to.

("pdfjs-dist": "2.5.207")
This works fine for me.

after 2 days on this issue I fixed it thanks to @yhunglee's comment.

So I have a CRA with react-scripts@4.0.3 and I installed:

"pdfjs-dist": "2.6.347",
"react-pdf": "5.3.2",

and then in the .jsx file I imported like this:

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

So for typings I didn't manage to make it work with @types/react-pdf so I declare the module manually in types.d.ts

declare module 'react-pdf/dist/esm/entry.webpack';

Hope this helps!

Hello. I have the same issue with Storybook and react-pdf 6.2.2.
And I can't find where i should edit Babel configuration...

Hola!
Any updates on this?

G'day - wondering if there is an ETA for this bug to be fixed? TIA

I had same issue in my React app with react-scripts 4.0.3
To render PDF instead of using this lib just used object Jsx tag

Sample usage

import pdfFile from '../../../test.pdf'; <object data={pdfFile} type="application/pdf" width="100%" height="100%"> </object>

I was getting this issue in another library pdf-viewer-reactjs@2.1.2 that installs pdfjs-dist@2.1.x. @Nubuck solution helped me to compile the project with Webpack, but my project was crashing because of an issue:

TypeError: Cannot read properties of undefined...

I added pdfjs-dist@@2.6.347 into package.json and also added "pdfjs-dist": "2.6.347" into yarn resolutions so pdf-viewer-reactjs uses pdfjs-dist@@2.6.347 instead of pdfjs-dist@2.1.x and everything works now.

If you want to solve this problem you need to switch to "react-pdf": "^5.3.2" version, this issure may be helpful for you, or see my codebox !!!!If the codebox runs incorrectly, it is possible to export the project run!!!!

I have this problem too, when I upgrade react-pdf to v6.2.0.
Any update ?

react: ^16.8.2,
react-pdf: 6.2.0,

./node_modules/pdfjs-dist/build/pdf.js 1198:17
Module parse failed: Unexpected character '#' (1198:17)
File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | }
    | class PDFDocumentLoadingTask {
      static #docId = 0;

| constructor() {
| this._capability = (0, _util.createPromiseCapability)();

react: 17.0.2,
react-pdf: 6.2.2,
typescript: 4.2.4,

./node_modules/pdfjs-dist/build/pdf.js 1198:17 Module parse failed: Unexpected character '#' (1198:17) File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | }
    | class PDFDocumentLoadingTask {
      static #docId = 0;

| constructor() { | this._capability = (0, _util.createPromiseCapability)();

react: 17.0.2, react-pdf: 6.2.2, typescript: 4.2.4,

just use 5.3.2

./node_modules/pdfjs-dist/build/pdf.js 1198:17 Module parse failed: Unexpected character '#' (1198:17) File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | }
    | class PDFDocumentLoadingTask {
      static #docId = 0;

| constructor() { | this._capability = (0, _util.createPromiseCapability)();
react: 17.0.2, react-pdf: 6.2.2, typescript: 4.2.4,

just use 5.3.2

But I need to use "devicePixelRatio" this props.
Is there any other way to use version 5.3.2 and change pixel ratio manual ?

./node_modules/pdfjs-dist/build/pdf.js 1198:17 Module parse failed: Unexpected character '#' (1198:17) File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | }
    | class PDFDocumentLoadingTask {
      static #docId = 0;

| constructor() { | this._capability = (0, _util.createPromiseCapability)();
react: 17.0.2, react-pdf: 6.2.2, typescript: 4.2.4,

just use 5.3.2

It really works.

./node_modules/pdfjs-dist/build/pdf.js 1198:17 Module parse failed: Unexpected character '#' (1198:17) File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | }
    | class PDFDocumentLoadingTask {
      static #docId = 0;

| constructor() { | this._capability = (0, _util.createPromiseCapability)();
react: 17.0.2, react-pdf: 6.2.2, typescript: 4.2.4,

just use 5.3.2

But I need to use "devicePixelRatio" this props. Is there any other way to use version 5.3.2 and change pixel ratio manual ?

import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = //cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js;

if you use create-react-app ,must add this
you can see my any sample https://gitee.com/garvinew/react-read-pdf-sample

If you want to solve this problem you need to switch to "react-pdf": "^5.3.2" version, this issure may be helpful for you, or see my codebox !!!!If the codebox runs incorrectly, it is possible to export the project run!!!!

This solution works for me, thanks a lot buddy!

Anything fixed in version 6?
In version 5 there is no TextLayer.css.

I fix this issue via updating react-scripts from @4.0.1 to @5.0.1

CRA 4 is now 2.5 years old, CRA 5 is almost 2 years old. I have no intention or capacity of supporting v4. If you need to use React-PDF with CRA 4, use older React-PDF versions.

I am using v7.3.3, but still getting this error.

ModuleParseError: Module parse failed: Unexpected character '' (1:0)

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

(Source code omitted for this binary file)

image

Nevermind, it works. The library looks good.

Nevermind, it works. The library looks good.

How did you make it work?

Ok, so apparently pdfjs-dist actually ships with builds for legacy browsers, but this needs to be imported differently, e.g.

import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf';

Perhaps it would be more prudent if react-pdf could import those legacy (more compatible) builds instead?

This was really helpful, thanks!

one possible solution,

import {pdfjs} from 'react-pdf';
import PDFJSWorker from 'pdfjs-dist/build/pdf.worker.entry';

pdfjs.GlobalWorkerOptions.workerSrc = PDFJSWorker;

Also set webpack.config.js
attributes alias
add
'pdfjs-dist': path.resolve(___dirname, 'node_modules/pdfjs-dist/legacy')

works good with webpack 4 and react 16 for react-pdf V6, if want to use V7 please use webpack5

Version5 has a case when I view one of a pdf files, It cause browser slow, lagging, and make it doesn't reposne. I've fixed the problem with upgrade to version 6 and found Module parse failed: Unexpected character '#'. when i update my nextjs version to "next": "^11.1.4" it fixed the error.
here my environment
"next": "^11.1.4"
"react": "^17.0.2"
"react-pdf": "^6.2.2"

add
transpileDependencies: ['pdfjs-dist']
in your vue.config.js if you use vue and pdfjs-dist

I managed to get react-pdf 6.2.2 to work with deps webpack 4.46.0 and @babel/preset-env 7.20.2

I found using the include property of the babel rule and adding pdfjs-dist after the source built and rendered successfully. Heres and snip of the webpack config for the rule:

const np = require('path')

module.exports = {
  // ...
  module: {
    // ...
    rules: [
      {
        test: /\.(mjs|jsx|js)$/,
        include: [
          np.resolve('src'),
          // babel-env has all the presets to build pdfjs, just needs to be included
          np.resolve('node_modules/pdfjs-dist/build'),
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              babelrc: false,
              configFile: false,
              presets: [
                '@babel/preset-env',
                // ....
              ],
              plugins: [
                '@babel/plugin-syntax-dynamic-import',
                // ...
              ],
            },
          },
        ],
      },
    ],
  },
}

I hope that helps someone that was also stuck on the Module parse failed: Unexpected character '#' (1413:9) build error

I managed to get react-pdf 6.2.2 to work with deps webpack 4.46.0 and @babel/preset-env 7.20.2

I found using the include property of the babel rule and adding pdfjs-dist after the source built and rendered successfully. Heres and snip of the webpack config for the rule:

const np = require('path')

module.exports = {
  // ...
  module: {
    // ...
    rules: [
      {
        test: /\.(mjs|jsx|js)$/,
        include: [
          np.resolve('src'),
          // babel-env has all the presets to build pdfjs, just needs to be included
          np.resolve('node_modules/pdfjs-dist/build'),
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              babelrc: false,
              configFile: false,
              presets: [
                '@babel/preset-env',
                // ....
              ],
              plugins: [
                '@babel/plugin-syntax-dynamic-import',
                // ...
              ],
            },
          },
        ],
      },
    ],
  },
}

I hope that helps someone that was also stuck on the Module parse failed: Unexpected character '#' (1413:9) build error

This solution worked for me. I installed "babel-loader": "^8.3.0" and added the below code into next.config.js (I use next.js 9.5.5)

config.module.rules.push({
test: /.(mjs|jsx|js)$/,
include: [
path.resolve('src'),
// babel-env has all the presets to build pdfjs, just needs to be included
path.resolve('node_modules/pdfjs-dist/build')
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
configFile: false,
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-syntax-dynamic-import']
}
}
]
});

Thank you so much!!!!

Another solution is using esbuild-loader with target es2015 , seems to fix most stuff.
Helped me bring react-pdf from v5 to v8

I specifically needed this line to make it work

            {
                test: /pdfjs-dist\/build\/pdf.js/,
                loader: 'esbuild-loader',
                options: {
                    target: 'es2015',
                },
            },

Babel seemed to be way messier

This is using
esbuild-loader : 4.2.0
react-pdf: 8.0.2