【问题标题】:Nuxt avoid import of client-side script for server-side renderingNuxt 避免为服务器端渲染导入客户端脚本
【发布时间】:2022-11-11 09:52:33
【问题描述】:

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

有没有办法从 SSR 中排除这个?

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

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

【问题讨论】:

标签: vue.js nuxt.js


【解决方案1】:

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

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

在您的示例中,这将是这样的

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

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多