luminaxster/syntax-highlighter

How can I use it with Next.js?

Closed this issue · 3 comments

import Highlighter from "monaco-jsx-highlighter";
this in next.js returns "document not found error" because window is not defined so I dynamically imported it.

 import dynamic from "next/dynamic";
const Highlighter = dynamic(import("monaco-jsx-highlighter"), { ssr: false });

This returns Loadable Component instead of Highlighter class.
How can I use this in next.js?

I see the confusion, this library is not component, next dynamic is about components not libraries, try a vanilla (standard) dynamic import:

let  jsxHighlighter = null;
import("monaco-jsx-highlighter").then((allMonacoSyntaxHighlighter)=>{
  jsxHighlighter=allMonacoSyntaxHighlighter.default;
  console.log(jsxHighlighter);
});

this worked in development but i am getting this error when I run npm run build:

info  - Collecting page data .(node:320312) UnhandledPromiseRejectionWarning: ReferenceError: document is not defined
    at s (/home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:5090)
    at p (/home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:6351)
    at l (/home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:5029)
    at e.exports (/home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:6753)
    at /home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:7789
    at /home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:20790
    at Object.<anonymous> (/home/tesla/Documents/projects/portfolio/client/node_modules/monaco-jsx-highlighter/dist/index.js:1:20811)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)

this is how implemented the import in the project:

let jsxHighlighter: any = null;
import("monaco-jsx-highlighter").then((allMonacoSyntaxHighlighter) => {
  jsxHighlighter = allMonacoSyntaxHighlighter.default;
});

When I comment out this code, I dont get any warning

This is not a problem with this library, this is a general case of using libraries in Next.js, I don't use it but this may wor:

import dynamic from "next/dynamic";
let  jsxHighlighter = null;
const HighlighterComponent = dynamic(()=>{
  
  import("monaco-jsx-highlighter").then((allMonacoSyntaxHighlighter)=>{
  jsxHighlighter=allMonacoSyntaxHighlighter.default;
  console.log(jsxHighlighter);
});

 return null;
}, { ssr: false });