You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monaco Editor React自动补全失效:添加tf.d.ts补全素材失败

解决Monaco Editor中TensorFlow.js类型自动补全失效问题

以下是针对你问题的具体修复方案,结合现有代码调整关键配置:

关键配置调整点

  • 开启语义验证:之前关闭语义验证会直接导致类型提示功能失效,必须开启。
  • 启用JS类型检查:针对JavaScript语言模式,需显式开启checkJs选项,让Monaco对JS文件进行类型分析。
  • 规范额外库路径:使用标准虚拟文件路径格式,避免Monaco解析异常。
  • 声明全局tf变量类型:明确告知Monaco全局tf变量的类型来源,确保自动补全关联到导入的tf.d.ts。

修改后的代码

import React, { useRef } from "react";
import Editor from "@monaco-editor/react";

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

  function handleEditorDidMount(editor, monaco) {
    editorRef.current = editor;

    // 调整诊断选项:开启语义验证
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
      noSemanticValidation: false, // 改为false,开启语义验证
      noSyntaxValidation: false,
    });

    // 调整编译器选项:开启JS类型检查,适配模块解析
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
      target: monaco.languages.typescript.ScriptTarget.ES2015,
      allowNonTsExtensions: true,
      checkJs: true, // 新增:开启JavaScript文件的类型检查
      moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    });

    // 添加额外类型库,使用标准虚拟路径
    monaco.languages.typescript.javascriptDefaults.addExtraLib(
      tfjsLib,
      "file:///tfjs.d.ts" // 使用标准file://格式的虚拟路径
    );

    // 声明全局tf变量的类型,关联到tf.d.ts中的定义
    monaco.languages.typescript.javascriptDefaults.addExtraLib(`
      declare const tf: typeof import('./tfjs').default;
    `, "file:///global.d.ts");
  }

  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() {
  const fs = require("fs");
  const path = require("path");
  const currentDir = path.join(process.cwd(), 'public');
  const fileContents = fs.readFileSync(path.join(currentDir, '/tf.d.ts'), 'utf8'); // 改用path.join避免路径拼接问题
  return {
    props: {
      tfjsLib: fileContents
    }
  }
}

额外排查建议

  1. 确认tf.d.ts文件内容完整且格式正确,可粘贴到VS Code中检查是否有类型定义语法错误。
  2. 若切换到TypeScript语言模式测试,需将defaultLanguage改为typescript,并使用monaco.languages.typescript.typescriptDefaults对应配置。
  3. 清除浏览器缓存后重新加载页面,避免Monaco缓存旧配置。

内容的提问来源于stack exchange,提问作者Gaba Miau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:37:08