首页 > 解决方案 > How can I import browser module in next.js without dynamic import

问题描述

 import Highlighter from "monaco-jsx-highlighter";

this import in next.js gives "document not found" error. So i tried to dynamically import

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

However dynamic import returns Loadable Component. I checked the next-github and looks like dynamic import works only for components. But import Highlighter from "monaco-jsx-highlighter". Highlighter is actually a class and needs to be initialized as :

const highlighter = new Highlighter()

How can I use this module in next.js without dynamic import?

标签: reactjsnext.jsserver-side-renderingmonaco-editordynamic-import

解决方案


我用 vanilla 动态导入而不是 next.js 动态导入解决了这个问题。

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

推荐阅读