search

Home  >  Q&A  >  body text

Nuxt method to avoid importing client-side scripts when rendering on the server side

In my nuxt.js application I have a script that imports NPM packages that are only compatible with browser contexts (it references document, location, window wait)

Is there a way to exclude it from SSR?

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

I can use the methods of process.client but the file is still imported into my component.

P粉518799557P粉518799557326 days ago434

reply all(1)I'll reply

  • P粉426906369

    P粉4269063692024-01-05 00:09:08

    You can import it dynamically instead of importing it in every context.

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

    In your example, it would look like this

    export default showThing(){
      if (process.client) {
        const thing = await import('@vendor/thing')
        thing()
      }
    }
    

    reply
    0
  • Cancelreply