neodynamic / JSPrintManager

Advanced Client-side Printing & Scanning Solution for Javascript
https://www.neodynamic.com/products/printing/js-print-manager/
257 stars 137 forks source link

Next.js - ReferenceError: document is not defined #48

Closed tmilciunas closed 2 years ago

tmilciunas commented 2 years ago

Hello, I am using Next.js and can't manage to load this library to work. It throws two errors:

First (warning):

./node_modules/.pnpm/jsprintmanager@5.0.1/node_modules/jsprintmanager/JSPrintManager.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Second (breaking error):

ReferenceError: document is not defined

~/node_modules/.pnpm/jsprintmanager@5.0.1/node_modules/jsprintmanager/JSPrintManager.js (2:41314)
~/node_modules/.pnpm/jsprintmanager@5.0.1/node_modules/jsprintmanager/JSPrintManager.js (2:513)
...

I am using jsprintmanager@5.0.1, package is being imported like so: import * as JSPM from 'jsprintmanager'.

Crashes happen with a simple line of JSPM.JSPrintManager.auto_reconnect = true anywhere in the code, so I can't debug it, since it crashes instantly.

tmilciunas commented 2 years ago

I've solved this issue by using Next.js dynamic import as it only renders on client-side where window is present, thus solving this issue like so:

// Define a component with jsprintmanager import

import * as JSPM from 'jsprintmanager'

export default const Print = () => {
  const print = () => {
    JSPM.JSPrintManager.auto_reconnect = true
    JSPM.JSPrintManager.start()

    // Your printing job
    ...
  }

  return <Button onClick={print} />
}
// Another component that actually needs printing functionality in it

import dynamic from 'next/dynamic'

// Import file with jsprintmanager import in client-side
const Print = dynamic(() => import('./print.tsx'), { ssr: false })

const ComponentThatNeedsPrinting = () => {
  return <Print />
}

Hopefully this can help to whomever runs into the same issue as me 😄