3

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.

1
  • Also, if your package could be used locally, do that rather than loading it globally. As explained here: stackoverflow.com/a/67751550/8816585 Commented Jul 22, 2022 at 20:21

1 Answer 1

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()
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i think there would be problems after the build.
@payam_sbr why would it? Should be all good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.