English 中文(简体)
为什么我获得参考资料:在我进口一个客户边的图书馆时,没有自我界定?
原标题:Why am I getting ReferenceError: self is not defined when I import a client-side library?

xterm反应部分载于Next.js。 当我无法接手错误信息时,我就坐下来了。

I m试图进口一个叫做xterm的npm客户-side模块,但如果我加上进口线,申请坠毁。

import { Terminal } from  xterm 

The error reads Server Error... ReferenceError: self is not defined and then shows this chunk of code as Source

module.exports = require("xterm");

根据我所做的一些研究,这必须涉及网络包,如果这样做的话,可以提供帮助:

output: {
  globalObject:  this 
}

Would you know how to fix this?

最佳回答

出现这一错误的原因是,图书馆需要网络信息预报系统,在服务器边的上没有。

阁下:<代码>xterm 试图进入服务器上没有的<代码>window物体。 解决办法是避免在服务器上装载<代码>xterm,并动态地进口该编码,使之只装上客户方。

下面是几个方面实现这一点的。


#1 Using dynamic import() inside useEffect

Move the import to your component s useEffect, then dynamically import the library and add your logic there.

useEffect(() => {
    const initTerminal = async () => {
        const { Terminal } = await import( xterm )
        const term = new Terminal()
        // Add logic with `term`
    }
    initTerminal()
}, [])

#2 Using next/dynamic with ssr: false

创建一种成分,使您添加<代码>xterm逻辑。

// components/terminal-component
import { Terminal } from  xterm 

function TerminalComponent() {
    const term = new Terminal()
    // Add logic around `term`
    return <></>
}

export default TerminalComponent

Then dynamically import that component when using it.

import dynamic from  next/dynamic 

const TerminalComponent = dynamic(() => import( <path-to>/components/terminal-component ), {
    ssr: false
})

作为备选案文,在动态地以<代码>next/dynamic进口图书馆时,您可直接添加这一逻辑,以避免为之提供额外档案。

import dynamic from  next/dynamic 

const Terminal = dynamic(
    {
        loader: () => import( xterm ).then((mod) => mod.Terminal),
        render: (props, Terminal) => {
            const term = new Terminal()
            // Add logic with `term`
            return <></>
        }
    },
    {
        ssr: false
    }
)
问题回答




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签