避免在服务器端渲染时导入客户端脚本的Nuxt方法
P粉518799557
P粉518799557 2024-01-04 09:57:53
[Vue.js讨论组]

在我的 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()
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号