I'm using CodeMirror to create an editor in my docusaurus website, and to use CodeMirror, you have to include some files from the package itself, which looks like this:
import { UnControlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/mode/javascript/javascript";
The problem is the third line, where I import the Javascript mode for code mirror. In that file, there references to browser specific APIs (navigator), so when I try to build the Docusaurus website, it tries to statically build the whole site and errors out saying
ReferenceError: navigator is not defined
Obviously, since that's not a thing in node. The website works fine in development mode btw...
So, what I want to do is to NOT load this file during the static building of the website, but instead only load that file on component mount. Here is what I tried:
useEffect(() => {
import("codemirror/mode/javascript/javascript");
}, []);
That did not work.
How can I load this file, only in the browser, and only once the component renders?
Edit: I also tried to use the <BrowserOnly/> component that comes with docusaurus, but that did not work either, it still showed the same error:
<BrowserOnly>
<Repl />
</BrowserOnly>
Solved:
I got the answer from a Github Issue Comment:
import React, { useEffect } from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";
if (typeof window !== "undefined") {
require("codemirror/lib/codemirror.css");
require("codemirror/mode/javascript/javascript");
}