2

In my nuxt.js application, I have a script that imports an NPM package which is only compatible with browser contexts (it references document, location, window, etc.)

Is there a way to exclude this from SSR?

import thing from "@vendor/thing"; // causes `document not defined` error
export default showThing(){
 if (process.client) {
    thing();
 }
}

I can use the method with process.client but this file is still imported in my components.

kissu
  • 40,416
  • 14
  • 65
  • 133
d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • Also, if your package could be used locally, do that rather than loading it globally. As explained here: https://stackoverflow.com/a/67751550/8816585 – kissu Jul 22 '22 at 20:21

1 Answers1

1

You could import it dynamically rather than in every context.

As explained in my answer here: https://stackoverflow.com/a/67825061/8816585

In your example, that would be something like this

export default showThing(){
  if (process.client) {
    const thing = await import('@vendor/thing')
    thing()
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133