Home > Net >  How to integrate Xterm.js with reactjs properly
How to integrate Xterm.js with reactjs properly

Time:12-03

So far I am not able to properly integrate xterm.js with reactjs due to which my code breaks in production but works while development. i need a proper way of importing xterm.js in component.

HELP !!!

import React, {useEffect} from 'react';
import {Terminal} from 'xterm';
import {FitAddon} from 'xterm-addon-fit';

const UITerminal = () => {
const term = new Terminal();
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);

useEffect(() => {
let termDocument = document.getElementById('terminal')
if (termDocument) {
term.open(termDocument)
fitaddon.fit();
}
window.addEventListener('resize', () => {
fitaddon.fit();
})
}, [])

return (<div id="terminal"></div>)

}

Below is the error response from production code. clearly it fails to import xterm

react_devtools_backend.js:4012 ReferenceError: Cannot access 'r' before initialization
at new m (96209.72626fc1cc862aea477a.bundle.js:1:165467)
at new b (96209.72626fc1cc862aea477a.bundle.js:1:159758)
at new M (96209.72626fc1cc862aea477a.bundle.js:1:57572)
at new r.exports.i.Terminal (96209.72626fc1cc862aea477a.bundle.js:1:294972)
at w (96209.72626fc1cc862aea477a.bundle.js:1:15994)
at zo (main.71e827eabc798023c129.bundle.js:1:1260000)
at Ws (main.71e827eabc798023c129.bundle.js:1:1333492)
at Wi (main.71e827eabc798023c129.bundle.js:1:1294411)
at Ui (main.71e827eabc798023c129.bundle.js:1:1294336)
at Pi (main.71e827eabc798023c129.bundle.js:1:1291367)

CodePudding user response:

The error shows that you might use Xterm before its initialization,

You might find it useful to use react-aptor or the idea behind it to connect pure js packages like Xterm.js into react world.

CodePudding user response:

It looks like the error you're encountering is related to the initialization of the Terminal class from xterm.js.

One potential solution to this issue could be to move the instantiation of the Terminal and FitAddon classes into the useEffect hook. This ensures that the Terminal and vFitAddon` objects are only created after the component has been mounted, which should prevent any issues with accessing uninitialized variables.

Here is an example of how your code could be updated to do this:

import React, { useEffect } from 'react';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';

const UITerminal = () => {
  useEffect(() => {
    const term = new Terminal();
    const fitAddon = new FitAddon();
    term.loadAddon(fitAddon);

    let termDocument = document.getElementById('terminal');
    if (termDocument) {
      term.open(termDocument);
      fitAddon.fit();
    }

    window.addEventListener('resize', () => {
      fitAddon.fit();
    });
  }, []);

  return <div id="terminal"></div>;
};
  • Related