How to use addExtraLib in Monaco with an external type definition

此生再无相见时 提交于 2019-12-03 03:12:37

After playing around a little I found a solution. Basically, the file has to be loaded using createModel with an explicit file URL. If you do this then the relative file path for node_module/@types works. Here's my working solution that can be used in the playground:

// compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    typeRoots: ["node_modules/@types"]
});

// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib(
    `export declare function next() : string`,
    'node_modules/@types/external/index.d.ts');

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

var jsCode = `import * as x from "external"
    const tt : string = x.dnext();`;

monaco.editor.create(document.getElementById("container"), {
    model: monaco.editor.createModel(jsCode,"typescript",new monaco.Uri("file:///main.tsx")), 
});

Joe's answer didn't work for me, fixed by prefixing the external type definition file path with file:///

Here's an updated example for the playground:

monaco.languages.typescript.typescriptDefaults.addExtraLib(
    'export declare function add(a: number, b: number): number',
    'file:///node_modules/@types/math/index.d.ts'
);

const model = monaco.editor.createModel(
    `import {add} from 'math';\nconst x = add(3, 5);\n`,
    'typescript',
    monaco.Uri.parse('file:///main.tsx')
);

monaco.editor.create(document.getElementById('container'), {model});

It's not necessary to provide the compiler options and diagnostic options.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!