Nexx
Nexx

Reputation: 407

Loading type definitions for all included files into Monaco editor

I'm currently developing a web based editor (for editing typescript files) using Monaco editor for the purpose and I'm facing a problem - How to load all typescript definitions for the included typescript files in order to have intellisense for them?

For example:

If my primary file is index.ts

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

console.log('index');

and the `test.ts

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

...

Is there any way to tell Monaco to include automatically the typescript definitions for 'test.ts' and 'test2.ts' files? Or I should follow the import statements somehow using typescript compiler API and import these definitions in the Monaco manually?

Upvotes: 3

Views: 1921

Answers (1)

Michael Hays
Michael Hays

Reputation: 6908

A good practice is to create a model for all of your source files. Place them in Monaco's virtual file system, and then it can figure all that import stuff out for you.

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});

Try pasting this into the playground: https://microsoft.github.io/monaco-editor/playground.html

Nit: When you import, you don't add the .ts to the end.

Upvotes: 3

Related Questions