【问题标题】:Loading type definitions for all included files into Monaco editor将所有包含文件的类型定义加载到 Monaco 编辑器中
【发布时间】:2022-03-19 04:24:10
【问题描述】:

我目前正在使用 Monaco 编辑器开发一个基于 Web 的编辑器(用于编辑打字稿文件),但我遇到了一个问题 - 如何加载包含的打字稿文件的所有打字稿定义以便对它们进行智能感知?

例如:

如果我的主文件是index.ts

import {test} from './test.ts';

console.log('index');

和`test.ts

import {test2} from './test2.ts';

...

有没有办法告诉摩纳哥自动包含'test.ts'和'test2.ts'文件的打字稿定义?或者我应该使用 typescript 编译器 API 以某种方式遵循导入语句并在 Monaco 中手动导入这些定义?

【问题讨论】:

    标签: monaco-editor typescript-compiler-api


    【解决方案1】:

    一个好的做法是为所有源文件创建一个模型。将它们放在 Monaco 的虚拟文件系统中,然后它可以为您计算出所有导入的东西。

    const sourceTest = [monaco.Uri.parse('file:///test.ts'), `
    import {test2} from './test2';
    export function test(message: string): string {
        test2.bar(\`foo \${message}\`);
    }`];
    
    const sourceTest2 = [monaco.Uri.parse('file:///test2.ts'), `
    export function test2(message: string): string {
        console.log(\`bar \${message}\`);
    }`];
    
    const sourceIndex = [monaco.Uri.parse('file:///index.ts'), `
    import {test} from './test'
    test('hello world');
    `];
    
    monaco.editor.createModel(sourceTest[1], 'typescript', sourceTest[0]);
    monaco.editor.createModel(sourceTest2[1], 'typescript', sourceTest2[0]);
    const model = monaco.editor.createModel(sourceIndex[1], 'typescript', sourceIndex[0]);
    monaco.editor.create(document.getElementById('container'), {model});
    

    尝试将其粘贴到 Playground 中: https://microsoft.github.io/monaco-editor/playground.html

    Nit:导入时,不要在末尾添加.ts

    【讨论】:

    • 嗨@michael,您知道是否有办法检测文件中的导入,然后尝试加载内容并按需创建模型?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多