将 JS 文件导入 Next JS - 出现引用错误

问题描述 投票:0回答:2

尝试在 Next JS 项目中导入 js 文件时出现以下错误。

错误: ReferenceError:导航器未定义

这是我用来插入文件的组件。我需要它来让 Codemirror 正确渲染 python,但该组件只有在删除 mode/python/python.js import

时才能工作
import Link from "next/link";
import { UnControlled as CodeMirror } from "react-codemirror2";
// import "../node_modules/codemirror/mode/python/python.js";
import "../node_modules/codemirror/lib/codemirror.css";
import "../node_modules/codemirror/theme/material.css";
import styled from "styled-components";

const CodeContainer = styled.div`
  position: absolute;
  width: 600px;
  left: 600px;
  height: 100%;
  overflow-y: auto;
  z-index: 1;
`;

const Code = () => (
  <CodeContainer>
    <CodeMirror
      value="<h1>Hello World</h1>"
      options={{
        mode: "python",
        theme: "material",
        lineNumbers: true
      }}
      onChange={(editor, data, value) => {}}
    />
  </CodeContainer>
);

export default Code;
reactjs next.js codemirror
2个回答
0
投票

你应该像这样动态导入 python-mode:

import dynamic from "next/dynamic";
 const dynamicPython= dynamic(() =>import("codemirror/mode/python/python.js"),{
     ssr:false,
 }); 

0
投票

import('codemirror/mode/python/python.js').then((module) => { /* Do something if needed */ });
块中,您可以执行导入模块所需的任何其他操作或配置。但是,在大多数情况下,您可能不需要执行任何特定操作,导入本身将负责设置 CodeMirror Python 模式。

import { useEffect } from 'react';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import '../node_modules/codemirror/lib/codemirror.css';
import '../node_modules/codemirror/theme/material.css';
import styled from 'styled-components';

const CodeContainer = styled.div`
  position: absolute;
  width: 600px;
  left: 600px;
  height: 100%;
  overflow-y: auto;
  z-index: 1;
`;

const Code = () => {
  useEffect(() => {
    // Dynamically import the Python mode only on the client side
    import('../node_modules/codemirror/mode/python/python.js').then((module) => {
      // You can perform additional actions here if needed
      // For example, you can log something to the console
      console.log('Python mode has been loaded:', module);
    });
  }, []);

  return (
    <CodeContainer>
      <CodeMirror
        value="<h1>Hello World</h1>"
        options={{
          mode: 'python',
          theme: 'material',
          lineNumbers: true,
        }}
        onChange={(editor, data, value) => {
          // Handle CodeMirror change event if needed
        }}
      />
    </CodeContainer>
  );
};

export default Code;

希望这能帮助您获得想要的输出;否则,它将帮助您确定确切的问题。

© www.soinside.com 2019 - 2024. All rights reserved.