volarjs / volar.js

💙🌊
https://volarjs.dev/
MIT License
994 stars 47 forks source link

Feature: Enable language server features in tagged template literals #83

Open Fuzzyma opened 11 months ago

Fuzzyma commented 11 months ago

Sometimes I have code in a string:

const js = `
  const msg = 'this doesnt have any language server features';
  console.log(msg);
`

There is a vscode extension that allows syntax highlighting for such template literals by prefixing it was a comment or use a tagged template:

// with comment
const js = /* javascript */ `
  const msg = 'this code is highlighted';
  console.log(msg)
`
// via tagged template
const js = javascript`
  const msg = 'this code is highlighted';
  console.log(msg)
`

Syntax highlighting alone is pretty cool. However, I run into bugs all the time because I have spelling errors or other easy to catch mistakes if those templates would also have language server support.

So I wanted to extend the ts language server to add this feature but I am not sure if extending a language server is even possible yet.

In a dream world you probably would use it like this:

const outerMsg = 'hello from outside'
const ts = javascript`
  // inherits the scope of the sorrounding code
  console.log(outerMsg); // outerMsg is "string"
`

const ts = javascript<Window>`
  // scope is Window
  window.console.log('much wow!')
`

Obviously you would still need to define the javascript function in this case. So maybe its not the best solution but its a start.

TylorS167 commented 9 months ago

I have a similar use case, but with the use of html in template strings. I'm also curious if it's possible to do this kind of thing with Volar

remcohaszing commented 8 months ago

Yes, this is possible. You will need to create a Volar language plugin. My recommended approach is to parse the TypeScript code into an AST using the TypeScript library. Then look for any template expressions, and create embedded code for each template expression found.

The following links may be useful as a reference implementation:

Some embedded languages are harded to deal with than others. TypeScript requires an entire project context, HTML/CSS/JSON does not. I’m positive this should be fairly simple to implement for embedded HTML, but you may run into issues implementing this for JavaScript/TypeScript.