簡體   English   中英

無法在 nextjs 中導入模塊

[英]Cannot import module in nextjs

我嘗試將縮放 websdk 模塊導入下一個 js,但它失敗了,因為 window object 未定義。

我所做的只是嘗試導入 websdk 模塊,但發生了這個錯誤

在此處輸入圖像描述

我將 nextjs v12 與 create-next-app 一起使用,我的代碼非常簡單。 這是我的pages/index.js

import { ZoomMtg } from '@zoomus/websdk';

const Page = () => {

    const handleClick = async () => {

    }

    return (
        <main>
            {/* get meeting number and role here (and password maybe) */}
            <button onClick={handleClick}>Join meeting</button>
            {/* <div>{meetingUrl && <ZoomWindow url={meetingUrl} />}</div>  */}
        </main>
    )
}

export default Page

websdk package 壞了還是什么?

請記住,NextJS 在瀏覽器和服務器上都運行。 在服務器端渲染期間, window 您可以使用動態導入僅導入瀏覽器上的一些依賴項,其中將定義 window。

https://nextjs.org/docs/advanced-features/dynamic-import

這是NextJS的示例

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home

你可以做同樣的事情,但你的依賴。

編輯:我認為 ZoomMtg 是一個組件。 文檔中的第一個示例更接近 ZoomMtg 所需的內容。

這樣的事情應該可以解決問題:

  const [zoomMtg, setZoomMtg] = useState(null)
  useEffect(() => {
   ( async () => {
     if(typeof window !== "undefined"){
      const {ZoomMtg} = (await import('@zoomus/websdk'))
      setZoomMtg(ZoomMtg)
    }
    })()
  }, [])

然后只需確認zoomMtg在渲染組件之前定義了 state 變量。 {!!zoomMtg && <YourComponent />

注意:如果您可以控制YourComponent模塊,那么更好的選擇是將ZoomMtg的導入移動到此文件並正常導入。 然后使用 nextjs dynamic語法導入YourComponent

我在導入模塊后在 nextjs 中遇到了同樣的問題,它會給出這樣的錯誤 - SyntaxError: Cannot use import statement outside a module。 如果你想在 nextjs 中不工作的情況下使用模塊,這是最好的解決方案,如果模塊不工作,這不是問題,只需配置設置 -

npm i next-compose-plugins 
npm i next-transpile-modules

next.config.js

const withPlugins = require("next-compose-plugins");
const withTM = require("next-transpile-modules")([
   "@project-serum/sol-wallet-adapter",
   "import another modules if not working..."
]);

module.exports = withPlugins([withTM], {
  pageExtensions: ["mdx", "md", "jsx", "js", "tsx", "ts", "cjs", "mjs"],
  distDir: "build",
  basePath: "",
  and config other... 
}

在 next.config.js 中進行此設置后,您可以使用模塊假設在組件中創建一個新文件 demo.js,然后它將工作。

演示.js

import Wallet from "@project-serum/sol-wallet-adapter";

我測試了這段代碼,它可以工作:

const Page = () => {

    const handleClick = async () => {
        alert("ok")
    }

    return (
        <main>
            {/* get meeting number and role here (and password maybe) */}
            <button onClick={handleClick}>Join meeting</button>
            {/* <div>{meetingUrl && <ZoomWindow url={meetingUrl} />}</div>  */}
        </main>
    )
}

export default Page

檢查您的@zoomus/websdk庫,然后

  • npm i在您的文件夾中
  • re-run your project

暫無
暫無

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

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