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

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

Closed
4 tasks done
sabotag opened this issue Aug 29, 2022 · 50 comments
Closed
4 tasks done
Labels
bug Something isn't working

Comments

@sabotag
Copy link

sabotag commented Aug 29, 2022

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 [email protected]

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
@sabotag sabotag added the bug Something isn't working label Aug 29, 2022
@wojtekmaj
Copy link
Owner

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 🤔

@quarryman
Copy link

quarryman commented Sep 8, 2022

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?

@wojtekmaj
Copy link
Owner

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

@FilipKittnar
Copy link

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

@wojtekmaj
Copy link
Owner

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

@wojtekmaj wojtekmaj changed the title react-pdf v6 Module parse failed: Unexpected character '#' [v6] Module parse failed: Unexpected character '#' Nov 11, 2022
@wojtekmaj wojtekmaj changed the title [v6] Module parse failed: Unexpected character '#' [v6] Module parse failed: Unexpected character '#' when using Create-React-App Nov 11, 2022
@SauravPatel3042
Copy link

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

@yhunglee
Copy link

yhunglee commented Nov 17, 2022

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

@victors1681
Copy link

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.

@veddermatic
Copy link

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
Copy link

clmz commented Dec 1, 2022

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

@Kajanan02
Copy link

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

@assdi54
Copy link

assdi54 commented Dec 6, 2022

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() {

@lag-of-death
Copy link

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

@apendua
Copy link

apendua commented Dec 13, 2022

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.

@apendua
Copy link

apendua commented Dec 13, 2022

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?

@wojtekmaj
Copy link
Owner

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.

@walpolsh
Copy link

walpolsh commented Dec 16, 2022

@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.

@sai-gillingham
Copy link

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

@evanjmg
Copy link

evanjmg commented Jan 4, 2023

Anyone have any build solutions?

@Nubuck
Copy link

Nubuck commented Jan 15, 2023

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

@aviadavi
Copy link

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

@briandiaz
Copy link

This is still failing...

@judebaptista18
Copy link

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

@maesiegrist
Copy link

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

@tukuna30
Copy link

tukuna30 commented Feb 15, 2023

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>

@AndrejGajdos
Copy link

I was getting this issue in another library [email protected] that installs [email protected]. @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 [email protected] and everything works now.

@ngwszsd
Copy link

ngwszsd commented Mar 3, 2023

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!!!!

@ShenHueTzu
Copy link

ShenHueTzu commented Mar 20, 2023

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,

@Realnaru
Copy link

./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,

@ngwszsd
Copy link

ngwszsd commented Mar 24, 2023

./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

@ShenHueTzu
Copy link

./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 ?

@yycfollow35
Copy link

./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.

@ngwszsd
Copy link

ngwszsd commented Apr 3, 2023

./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

@Novizh
Copy link

Novizh commented Apr 5, 2023

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!

@cdk0507
Copy link

cdk0507 commented May 2, 2023

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

@fr11nik
Copy link

fr11nik commented Jun 29, 2023

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

@wojtekmaj
Copy link
Owner

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.

@wojtekmaj wojtekmaj closed this as not planned Won't fix, can't repro, duplicate, stale Jul 26, 2023
@Granddevv
Copy link

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

@Granddevv
Copy link

Nevermind, it works. The library looks good.

@aziz1234
Copy link

Nevermind, it works. The library looks good.

How did you make it work?

@rramos-j
Copy link

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!

@lingduzero
Copy link

lingduzero commented Oct 25, 2023

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

@MachuKP
Copy link

MachuKP commented Nov 1, 2023

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"

@nettieJin
Copy link

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

@pachopa
Copy link

pachopa commented Jun 4, 2024

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!!!!

@romanpastu
Copy link

romanpastu commented Jul 12, 2024

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

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

No branches or pull requests