避免在伺服器端渲染時匯入客戶端腳本的Nuxt方法
P粉518799557
P粉518799557 2024-01-04 09:57:53
0
1
402

在我的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學習者快速成長!