避免在服务器端渲染时导入客户端脚本的Nuxt方法
P粉518799557
P粉518799557 2024-01-04 09:57:53
0
1
405

在我的 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粉518799557
P粉518799557

全部回复(1)
P粉426906369

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

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

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

export default showThing(){
  if (process.client) {
    const thing = await import('@vendor/thing')
    thing()
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!