簡體   English   中英

動態導入 - NextJS

[英]Dynamic Imports - NextJS

我有一個加載腳本的簡單函數:

const creditCardScript = (
  onReadyCB,
  onErrorCB,
) => {
  let script = document.createElement("script");
  script.type = "text/javascript";
  script.src = process.CREDIT_CARD_SCRIPT;
  document.head.appendChild(script);

  script.onload = function() {
    ...
  };
};

export default creditCardScript;

在遷移到 NextJS 之前,我使用以下命令import creditCardScript from "./creditCardScript"腳本: import creditCardScript from "./creditCardScript"

Sine NextJS 在 Node 中呈現組件服務器端,需要注意確保任何引用window (特定於瀏覽器)的代碼在componentDidMount之前不會被調用。

NextJS 通過提供動態導入(圍繞react-loadable的包裝器)解決了這個問題:

  • 僅在需要時加載組件,
  • 提供僅在客戶端加載組件的選項( ssr: false )。

我繼續實施動態導入:

const creditCardScript = dynamic(import("./creditCardScript"), { ssr: false });

componentDidMount

componentDidMount = () => {
  creditCardScript(
    this.onReadyCB,
    this.onErrorCB
  );
};

但我得到了這個: Uncaught TypeError: Cannot call a class as a function

我試圖將函數轉換為類並使用構造函數傳入args ,但我的代碼現在無聲無息地失敗了。

正如尼爾在評論中提到的,我需要做的就是在componentDidMount做這樣的事情:

const { default: creditCardScript } = await import("./creditCardScript"); 

鏈接到官方教程

導出默認僅適用於import from語句,您可以嘗試

export creditCardScript;

在導入時,你可以這樣使用

const {creditCardScript} = dynamic(import("./creditCardScript"), { ssr: false });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM