Nuxt method to avoid importing client-side scripts when rendering on the server side
P粉518799557
P粉518799557 2024-01-04 09:57:53
0
1
399

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粉518799557
P粉518799557

reply all(1)
P粉426906369

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()
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!