根据@摩纳哥编辑器/react的文档,我们需要原始摩纳哥编辑器作为对等依赖。我将其安装为一个dev依赖项,并试图将node_modules/monaco-editor/monaco.d.ts添加到include块中的tsconfig.json中。但在此之后,我仍然无法访问类型声明。我唯一能让它工作的方法就是像这样导入它。
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
但是现在,当我试图为editor和monaco变量定义它们时,我的类型声明会抛出错误。有人知道热身能让它们正常工作吗?
下面是我在定义类型时的代码。
import { useState, useRef } from 'react';
import Editor from '@monaco-editor/react';
import styles from '../Code.module.css';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
type Language = {
languageName: string;
languageID: number;
};
type EditorProps = {
language: Language;
onCodeChange: Function;
};
type Monaco = typeof monaco // to use it as a type for the monaco variable in handleEditorDidMount function
const CodeEditor = ({ language, onCodeChange }: EditorProps) => {
console.log('language is ', language);
const [editorValue, setEditorValue] = useState('//some comment');
const editorRef = useRef(null);
const monacoRef = useRef(null);
const handleEditorDidMount = (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {
editorRef.current = editor;
monacoRef.current = monaco;
console.log(monaco.languages.getLanguages());
console.log('editor', editor.getModel().getLanguageIdentifier().language);
};
const handleEditorValueChange = (value: string|undefined) => {
//console.log('event is ', event);
setEditorValue(value);
};
const editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
fontSize: 15,
minimap: {
enabled: true,
},
};
return (
<div className={styles.editorBlock}>
<div className={styles.editorNav}>
<button>Submit</button>
<button>Change Language</button>
</div>
<Editor
height="90vh"
language={language.languageName}
defaultValue={editorValue}
onMount={handleEditorDidMount}
onChange={handleEditorValueChange}
options={editorOptions}
/>
</div>
);
};在我的handleEditorDidMount函数中,参数摩纳哥抛出错误,不能使用导入作为类型
发布于 2021-12-08 08:17:28
您在代码中做了许多错误的假设。
导入类似普通模块的输入文件的
import { languages, editor } from "monaco-editor/esm/vs/editor/editor.api";之类的东西。这将导入两个名称空间Editor.monaco和languages模块react-摩纳哥导出MonacoEditor,而不是Editor.monaco(正如您导入的那样)只是来自摩纳哥模块的导出对象。你对“摩纳哥类型”的期待是什么?monaco的引用应该包含什么?React中的引用持有指向对象的指针,这些对象要么是在DOM中实例化的,要么是React组件的实例。让这个引用用于摩纳哥导出毫无意义。。
<MonacoEditor
ref={this.editorRef}
language={language}
options={opts}
/>因此,您不需要挂载函数来设置它。
https://stackoverflow.com/questions/70261303
复制相似问题