NodeJS 摩纳哥编辑器react automcomplete不工作

iaqfqrcu  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(338)

我有一个名为tf.d.ts的文件,其中包含所有类型脚本的定义,我想将其作为自动完成材料添加到Monaco编辑器中。不管我怎么尝试,它仍然不会工作。自动完成不工作。

import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import Editor from "@monaco-editor/react";
import * as me from "monaco-editor"

function TensorFlowEditor({ tfjsLib }) {
  const editorRef = useRef(null);

  async function handleEditorDidMount(editor, monaco) {
    editorRef.current = editor;
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
      noSemanticValidation: true,
      noSyntaxValidation: false,
    });

    // compiler options
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
      target: monaco.languages.typescript.ScriptTarget.ES2015,
      allowNonTsExtensions: true,
    });
    monaco.languages.typescript.javascriptDefaults.addExtraLib(tfjsLib, "ts:filename/tfjs.d.ts");
    console.log(monaco.languages.typescript.javascriptDefaults.addExtraLib.toString())
  }

  function runCode() {
    const tf = require('@tensorflow/tfjs');
    console.log(eval(editorRef.current.getValue()))

  }
  let defaultCode = `
  
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  model.predict(tf.tensor2d([5], [1, 1])).print();
  // Open the browser devtools to see the output
});

  `
  return (
    <>
      <button onClick={runCode}>Run Code</button>
      <Editor
        height="90vh"
        defaultLanguage="javascript"
        defaultValue={defaultCode}
        theme="vs-dark"
        onMount={handleEditorDidMount}
      />
    </>
  );
}
export default TensorFlowEditor

export async function getStaticProps() {
  var fs = require("fs")
  var path = require("path")
  const currentDir = path.join(process.cwd(), 'public');
  const fileContents = fs.readFileSync(currentDir + '/tf.d.ts', 'utf8');
  return {
    props: {
      tfjsLib: fileContents
    }
  }
}

我希望自动完成能工作。我尝试更改为typescriptDefault,我尝试在typescript和javascript之间更改语言,我尝试不使用最后一个路径参数。文件读取正确,我用console.log检查,我尝试使用标记useLib=false,true。

f1tvaqid

f1tvaqid1#

我也有同样的问题。我不是100%确定为什么这不像文档所说的那样工作,但是使用createModel方法代替了使用addExtraLib方法对我来说是有效的。

monaco.editor.createModel(`declare const myname: () => "garrett"`, 'typescript', monaco.Uri.parse('./types.d.ts'))

使用这个方法,我能够让Intellisense注册我的类型并提供自动完成。我发现在Monaco中查看该文件时,类型可以正常工作,因此我使用types.d.ts文件作为默认路径初始化编辑器,然后切换到主文件。这感觉真的很hacky。
我还应该提到我正在使用https://github.com/react-monaco-editor/react-monaco-editor
另一个潜在的有用的东西,任何人谁遇到这一点。在我的情况下,我正在努力让全局类型与Jest/test文件和Monaco一起工作,并且在挂载后使用createModal方法后,我能够获得自动完成和建议。下面是React的例子。

import Editor from '@monaco-editor/react'

const MyEditor = () => {

  const handleEditorWillMount = (editor, monaco: Monaco) => {
    monaco?.languages.typescript.javascriptDefaults.setEagerModelSync(true)

    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
      noSemanticValidation: true,
      noSyntaxValidation: false,
    })

    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
      target: monaco.languages.typescript.ScriptTarget.ES2016,
      allowNonTsExtensions: true,
      allowJs: true,
      moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
      module: monaco.languages.typescript.ModuleKind.ESNext
    })

    // THIS IS WHAT GOT AUTO COMPLETION WORKING FOR ME
    // In my actual file, I replace the first argument with the `@types/jest` declaration file
    monaco.editor.createModel('declare const myname: () => "garrett"', 'typescript', monaco.Uri.parse('./types.d.ts'))
  }

  return (
   <Editor
     defaultLanguage="typescript"
     defaultValue={file}
     onChange={(value) => handleFileInput(fileName, value ?? '')}
     path={fileName}
     theme="vs-dark"
     options={{
       minimap: {
         enabled: false,
       },
     }}
     className="h-100"
     onMount={handleEditorWillMount}/>
  )
}

相关问题