首頁  >  問答  >  主體

避免在伺服器端渲染時匯入客戶端腳本的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 天前406

全部回覆(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
  • 取消回覆