'Vscode: create a language service extension that runs typescript on custom files

I started a vscode extension project by running yo code and chose "New Language Support", just like vscode docs.

yo code

Then, I configured the syntax json file to include "source.ts" to highlight everything as typescript:

{
    "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
    "name": "Sample",
    "fileTypes": [
        "sample"
    ],
    "patterns": [
        {
            "include": "source.ts"
        }
    ],
    "repository": {},
    "scopeName": "source.sample"
}

And it works:

sample.sample

The problem is that I only have the highlight syntaxes and I wished that it could run typescript server to check types and show IntelliSense code.

My question is: how can I create a simple vscode language service to apply typescript on the ".sample" files?



Solution 1:[1]

I found a way of doing it by embedding the files and sending them to typescript using middleware.

The problem is that typescript does not include it in the workspace so you will have limited features. For example, intelliSense will only be for local variables.

This is how to implement it:

  const clientOptions: LanguageClientOptions = {
    documentSelector: [{ scheme: "file", language: "sample" }],
    middleware: {
      provideCompletionItem: async (document, position, context) => {
        // get a virtual uri for embedded language and create a map to 
        // reference back to the original file.
        // virtualUri: `embedded-content://ts/${originalUri}.ts`
        const virtualUri = getEmbeddedUri(document);

        const result =
          await vscode.commands.executeCommand<vscode.CompletionList>(
            "vscode.executeCompletionItemProvider",
            virtualUri,
            position,
            context.triggerCharacter
          );
        return result;
      },

Here you can check a full list of vscode commands: https://code.visualstudio.com/api/references/commands

And if you want to check a full example, this is an old commit that I implemented this way: https://github.com/estrelajs/estrela-vscode/tree/b9ac21b33daae09fd32ced93a5f2e4adf36c960a

The real way of doing it is creating a Language Server using the typescript language service library that comes on the typescript package. If you want to know more about, check out the svelte language service repository: https://github.com/sveltejs/language-tools/tree/master/packages/language-server

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eduardo Rosostolato