ng2-pdf-viewer - Angular Universal (Express Engine)

474 views Asked by At

I am using Angular standalone component (no modules) with Angular Universal (Express Engine). I added ng2-pdf-viewer but when I start the server, I am getting the below error:

./node_modules/canvas/build/Release/canvas.node:1:0 - Error: 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)

My package.json is as below:


  "dependencies": {
    "@angular/animations": "^16.2.0",
    "@angular/cdk": "^16.2.9",
    "@angular/common": "^16.2.0",
    "@angular/compiler": "^16.2.0",
    "@angular/core": "^16.2.0",
    "@angular/forms": "^16.2.0",
    "@angular/material": "^16.2.9",
    "@angular/platform-browser": "^16.2.0",
    "@angular/platform-browser-dynamic": "^16.2.0",
    "@angular/platform-server": "^16.2.0",
    "@angular/router": "^16.2.0",
    "@ngneat/hot-toast": "^6.0.1",
    "@ngneat/overview": "^5.1.0",
    "@nguniversal/express-engine": "^16.2.0",
    "aos": "^2.3.4",
    "express": "^4.15.2",
    "ng2-pdf-viewer": "^10.0.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.13.0"
  },

When I started the server with ng serve, it works fine. The issue I think is with dev:ssr (or with universal only)

Tested it with Angular 17.0.0 (standalone + Angular SSR this time) as well as below:

"dependencies": {
    "@angular/animations": "^17.0.0",
    "@angular/common": "^17.0.0",
    "@angular/compiler": "^17.0.0",
    "@angular/core": "^17.0.0",
    "@angular/forms": "^17.0.0",
    "@angular/platform-browser": "^17.0.0",
    "@angular/platform-browser-dynamic": "^17.0.0",
    "@angular/platform-server": "^17.0.0",
    "@angular/router": "^17.0.0",
    "@angular/ssr": "^17.0.0",
    "express": "^4.18.2",
    "ng2-pdf-viewer": "^10.0.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.2"
  },

The error is more clear there:

node_modules/pdfjs-dist/build/pdf.js:8671:35: 8671 │ const Canvas = require("canvas"); ╵ ~~~~~~~~

You can mark the path "canvas" as external to exclude it from the bundle, which will remove this error and leave the unresolved path in the bundle. You can also surround this "require" call with a try/catch block to handle this failure at run-time instead of bundle-time.

Clearly it is something with canvas. Not sure how to fix this. Any thoughts?

0

There are 0 answers