首页  >  问答  >  正文

避免在服务器端渲染时导入客户端脚本的Nuxt方法

在我的 nuxt.js 应用程序中,我有一个脚本导入仅与浏览器上下文兼容的 NPM 包(它引用 documentlocationwindow 等)

有没有办法将其从 SSR 中排除?

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

我可以使用 process.client 的方法,但该文件仍然导入到我的组件中。

P粉518799557P粉518799557289 天前412

全部回复(1)我来回复

  • P粉426906369

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

    您可以动态导入它,而不是在每个上下文中导入它。

    正如我在这里的回答所解释的:https://stackoverflow.com/a/67825061/8816585

    在你的例子中,会是这样的

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

    回复
    0
  • 取消回复