sveltejs / language-tools Goto Github PK
View Code? Open in Web Editor NEWThe Svelte Language Server, and official extensions which use it
License: MIT License
The Svelte Language Server, and official extensions which use it
License: MIT License
Is your feature request related to a problem? Please describe.
When adding or refactoring routed .svelte files in Sapper, it is quite tedious to use the correct import path for components. Is it "../components/View.svelte" or "../../components/View.svelte", etc...
Describe the solution you'd like
Auto component import: when I start typing <View
into a .svelte file, I would like a tooltip offering to import matching component(s).
Additionally, when refactoring, I would like the editor to ask if I would like to update import paths as it does with Angular, for example.
Describe alternatives you've considered
An alternative would be to support the use of rollup-plugin-alias as seen in https://github.com/sveltecasts/010-rollup-alias/blob/master/rollup.config.js#L18 so that we can simply type import View from "@components/View.svelte";
Note that I'm using a simpler implementation of rollup-plugin-alias:
const aliases = alias({
resolve: ['.jsx', '.js', '.tsx', '.ts', '.svelte'],
entries: [
{ find: '@components', replacement: `${__dirname}/src/components`},
{ find: '@routes', replacement: `${__dirname}/src/routes`},
]
})
And it would be even more awesome if BOTH could be supported. Thanks for the great work!
Currently, script tags are extracted no matter where they are within the svelte component. But only the top-level script should be treated as the instance script.
Test cases:
{#if name}
<script>
console.log('I should not be treated as top level')
</script>
{/if}
<script>
let name = 'I am top level!';
</script>
{@html `<script type="application/ld+json">${JSON.stringify(iAmNotTopLevel)}</script>`}
Extractor is in https://github.com/sveltejs/language-tools/blob/master/packages/language-server/src/lib/documents/utils.ts
This is the reference repo: https://github.com/RyanCavanaugh/learn-a/
You could then have a yarn watch
command at the root of the repo and it would propagate through all sub-packages.
Right now you need to cd
to that sub-folder to get that working.
You have this code:
<p>bla</p>
<!--<style>h1{ color: blue; }</style>-->
<style>p{ color: blue; }</style>
Bug: The extractor does not know the first style tag is commented out and still extracts it.
Solution: Enhance the regex to ignore styles/scripts that are commented out.
Are we ready to have people start using https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode ?
https://github.com/sveltejs/integrations points to the old plugin location at https://marketplace.visualstudio.com/items?itemName=JamesBirtles.svelte-vscode
The old plugin has about 90x as many installs. I'm wondering how we can notify these users that there's a new plugin. Some ideas in order of effectiveness:
And build green
Is your feature request related to a problem? Please describe.
Many people seem to have problems setting up preprocessors for the plugin - I guess partly because they install the extension and just expect it to work.
Describe the solution you'd like
Maybe we can get more robust/user friendly by doing the following things:
svelte.config.js
, we just do a best guess by using https://github.com/kaisermann/svelte-preprocesslang="typescript"
in script? have you setup preprocessors correctly? see <somelink> for more info"Describe alternatives you've considered
Make docs clearer.
This thread is intended for an overview of approaches on how to implement a language server for svelte files. Discussion on a prefered solution can be done here aswell.
Currently syntax highlighting and some basic autocompletion works for svelte files.
Rich intellisense however is not provided, does not know about all the typescript files in the workspace, and also has no type information about the svelte components.
The same is true for the html part where special svelte syntax is highlighted but intellisense is not working. The vscode-html-languageservice is used which does not know about the special syntax by default.
The current language server does use the svelte compiler for parsing files and getting diagnostics like "no alt attribute on this img tag".
A more indepth analysis: Comment
Disclaimer: I'm not the author of any of the existing solutions, I did look at the code however. If some of the information is wrong or not detailed enough, or you are missing a solution, feel free to comment, I will adjust it.
Uses htmlparser2 to parse the html part of a svelte file. Uses hooks of the html parser to add custom parsing and extract relevant information.
Uses espree to parse the script parts of a svelte file. Then walks the AST to extract relevant information.
Provides the results in a JSON-Format.
https://github.com/ArdenIvanov/svelte-intellisense uses it to parse svelte files. It uses the result to attach some additional behavior.
Since this uses a javascript parser, it will not work with typescript.
Uses svelte's compiler to parse the HTMLx part of a svelte component. Then transforms the HTMLx plus the original script part to a tsx file with a self-written transformer.
https://github.com/simlrh/svelte-language-server/blob/feature/extend-ts-support/src/plugins/ts-svelte/service.ts (a fork from svelte-language-server) uses it to create shadow-tsx-files of svelte-files. It then uses typescript's language service, but proxies the requests: It replaces the original file path with the file path to the generated tsx-file. The typescript language server therefore checks the generated tsx files. Results are transformed back to get correct document positions.
https://github.com/halfnelson/svelte-type-checker-vscode is another language server using the svelte2tsx-library.
Description taken from implementer's comment:
Compiler:
It consumes the exported variables and functions from inside a Svelte script, and then generates it as a declaration files which contains a class that extends the runtime SvelteComponent.
Typechecker:
See comments of this thread.
Any tag that starts with style
or script
is wrongfully treated as a script/style tag.
<!-- should be extracted -->
<style>h1{color:blue}</style>
<!-- should not be extracted -->
<styless></styless>
<p>I'm below the styless component. Since the parser wrongfully thinks that was a style opening tag, I get css linting errors now</p>
Also see jamesbirtles/svelte-language-server#21
Extractor is in https://github.com/sveltejs/language-tools/blob/master/packages/language-server/src/lib/documents/utils.ts
Describe the bug
There doesn't appear to be an option available to organize imports if currently within a svelte file.
To Reproduce
Hit shift cmd P and search for organize imports, it doesn't display any suggestion.
Expected behavior
A clear and concise description of what you expected to happen.
System (please complete the following information):
Additional context
Works on javascript files
Describe the bug
Source mapping is wrong when you comment out script
.
To Reproduce
Add "checkJs": true
to jsconfig.json
/ tsconfig.json
<!-- <script>
const bla = true;
</script> -->
<Navigation />
Will do red ("cannot find Navigation") squiggels at script
, not at Navigation
.
Expected behavior
Everything should work the same as if script is not commented out
System (please complete the following information):
Additional context
Maybe that's something inside svelte2tsx
, not honoring the comment and thinking there is a script
tag.
Describe the bug
Some weird autocompletion happens, especially when using ( )
<script>
// I import some objects/components/functions...
import { Button } from '@UI';
...
// Then for example I write an `if`
// and the autocompletion becomes weird
if Button() // <- I have the Button that is put even if I didnt select it
for example. There seems to be a lot of weird autocompletion going on. Above case is from someone else on the discord but I started experiences such weird autocompletion while writing code yesterday. Will update the issue when I track down more cases when it happens.
Expected behavior
Correct autocompletion like in Svelte plugin by James Birtle, had no issues there.
System (please complete the following information):
Describe the bug
svelte2tsx use's svelte's parser/compiler. The AST shape for awaitblocks changed here:
sveltejs/svelte@7d1e4e8#diff-eff8bd2281855180f438ed2314a5d534
Svelte2tsx is pinned to svelte 3.16 and only supports the value:string property. We need to update to handle the de structuring now available
To Reproduce
bump svelte package dependency to 3.22+ and run tests in svelte2tsx
Maybe we need that to work with the community.
The current implementation contains code for dealing with Svelte 2 files. Do we really support Svelte 2 going forward? I feel that this would be a lot of work. Maybe remove the Svelte 2-related code?
{
"name": "@sveltech/routify",
"version": "0.0.0-development",
"description": "Routes for Svelte, automated by your filestructure",
"main": "lib/index.js",
"svelte": "runtime/index.js",
The svelte key is what is being resolved within Svelte apps, but code completion doesn't work, since VSCode uses the main key.
Could not find a declaration file for module '@sveltech/routify'. '... routify/lib/index.js' implicitly has an 'any' type.
Originally posted by @jakobrosenberg in #9 (comment)
As @jakobrosenberg point out. The svelte key in external module's package.json
is a special custom main entry for svelte component source. See rollup-plugin-svelte for more info. This custom entry should be consider when resolving svelte module
Is your feature request related to a problem? Please describe.
Add a new package to the mono-repo which could be something like svelte-check
. Perhaps being extra verbose is good here, because I'm not certain that in the long term this module would be the place where it lives. (e.g. I think if there's a svelte
cli, then this would be a subcommand in there.
Describe the solution you'd like
The package would use the LSP shipped in this repo to ping every Svelte file in the current directory, and to request diagnostics (a.k.a errors) for that file. This is effectively the equivalent of running TypeScript and/or other tools we support in the LSP over each file.
Describe alternatives you've considered
In theory this could be built without the LSP, but that abstraction is solid and already has proven itself in vetur
Additional context
Came out of sveltejs/svelte#4518 (comment)
I have the Svelte Beta extension installed and have restarted the language server. My svelte.config.js
is:
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess(),
};
However, the extension does not seem to help VS Code understand that my code is Typescript, since it gives an error on type annotation:
Type annotations can only be used in TypeScript files. javascript
Also interesting, if I change lang="typescript"
to type="text/typescript"
, the syntax colours completely go away, as well as the error:
System (please complete the following information):
Describe the bug
Error in VSCode, but everything is compiled and functional.
The error say: "Module '"/home/scippio/..../src/Test.svelte"' has no default export.ts(1192)"
App.svelte
<script type="text/typescript">
import Test, { getText } from './Test.svelte'
export let name: string = 'world'
console.log(Test)
</script>
<h1>Hello {name}! this is: {getText()}</h1>
<Test></Test>
Test.svelte
<script context="module" type="text/typescript">
export function getText(): string {
return "getText called..."
}
</script>
<script type="text/typescript">
import { onMount } from 'svelte'
onMount(async () => {
console.log("Test init...")
})
</script>
<b>just test</b>
svelte.config.js
// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess({
typescript: {
// transpileOnly: true
// allowSyntheticDefaultImports: true
}
// ...svelte-preprocess options
}),
// ...other svelte options
};
Version: 1.46.0-insider
Commit: 6849775440496504e0677ffcf2a46d47ad9130f5
Date: 2020-05-15T05:29:39.210Z
Electron: 7.2.4
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Linux x64 5.4.40-1-lts
Is your feature request related to a problem? Please describe.
Currently, I cannot do rename refactorings in svelte files.
Describe the solution you'd like
Allow rename refactorings inside svelte files to work so that
Additional context
I started prototyping this. Renames of variables/functions inside svelte files can be implemented quickly.
However implementing prop renames requires changes to svelte2tsx
. It seems that right now there is no mapping from export let X
to the generated jsx-prop.
Another problem is that when you do a rename inside ts/js, the language server does not pick that up because he is only registered to react to changes of svelte files. To fix that, it would need to register for js/ts files, too, which requires some work to differ between svelte and ts/js documents and not for example run diagnostics of the HTMLPlugin
on js/ts files. Maybe this could come as a second step, after renaming inside svelte files works.
#await then doesn't seem to be supported
Example code:
{#await foo()}
.....
{:then}
async function completed successfully!
{:catch err}
async function failed:(
{/await}
{:then} will be showed with an error, but it shouldn't as far as i know
I installed the svelte-language-server
package and tried running it both without arguments:
$> node_modules/.bin/svelteserver
and with --stdio
$> node_modules/.bin/svelteserver --stdio
In both cases nothing happens. The command just exits immediately without any output. Exit code is also 0.
My current tech stack is Angular + Pug + Stylus. I would like to explore moving to Svelte, but it would be infeasible for me to move off of Pug. Stylus is a nice bonus too.
I believe I was able to get the preprocessor to do what I needed, but the lack of decent VSCode support was a deal breaker. I'm super glad this project is taking off!
In summary: please add some sort of pug and stylus support to the language processor and vscode. Thanks!
Hello!
If i understand correctly, this is the official repo for VSCode Svelte extension, and UnwrittenFun's repo is not maintained anymore.
There are quite a few issues in the legacy repo that raise the issue of incorrect SCSS linting within the extension, and it seems this problem is still present in this official extension.
To quote a few:
jamesbirtles/svelte-vscode#103 (comment)
jamesbirtles/svelte-vscode#113
Are there some instructions we are still missing to allow clean linting of SCSS in .svelte
files ?
This is an overview of the current state of the svelte-language-server
- what it already can do, what it cannot, yet. If you feel a feature is missing or something that should work according to this list does not work, open a new issue.
<svelte:window>
#await
<svelte:window>
#await
:global
tagclass
that are present in css (#844)class
to css$: ...
and $variableSubcribeShortHand
) (#57)//@ts-check
/ //@ts-nocheck
d.ts
definition (#1057)See sveltejs/svelte#4818.
During editing, the likelihood that the code is invalid is very high. But the svelte compiler is designed to throw syntax errors to warn the user. Thus the features that rely on the svelte compiler won't work when there's a syntax error.
We did consider writing a dedicated parser for the editor but that seems to be too much work and maintenance burden. So it's not a priority, but we don't say it won't ever happen.
The Typescript's language service is mostly synchronous so we can't preprocess code before handing it off to svelte2tsx
, because that's asynchronous (#339). That hinders features such as better Pug support. That's also one of the big roadblocks of eslint-plugin-svelte3
. A svelte.preprocessSync
might help, but was decided against for now.
Another problem that arises from the synchronous language service is the effort required to implement a TypeScript plugin (#580) which would help crossing the boundaries of TS/JS/Svelte and enable features such as "start rename in a TS file, Svelte files get updated, too". Even if we ignore preprocessing, the process of intellisense is still asynchronous because we use source-map
to map the source code positions which is asynchronous.
Copy from origin repo jamesbirtles/svelte-language-server#8, this issue still exists.
Vetur keep cache of ScriptSnapShot and document version of none vue files and update when file updated.
https://github.com/vuejs/vetur/blob/master/server/src/services/typescriptService/serviceHost.ts
I tried to increase the version every time when ts host request version, the problem resolved but the performance is crippled by it. So this issue is related to document version and ts's incremental compilation. Due to performance issue we have to implement a similar incremental compilation solution like vetur does, keep cache of none svelte document and only update version when file actually changes.
Describe the bug
Not quite sure if its within the scope of the Svelte
plugin but:
If you have:
<div class="form-field"></div>
And try to do class selector within the style tag like:
<style>
.form-field {
color: red;
}
</style>
Just starting with "." in the <style>
gives you gibberish suggestions for autocompletion.
Expected behavior
I've tried the same within normal .html
file and behavour there is as such: "form" selector works normally, but for words starting with "." it is completly disabled, same with #.
It would be nice to have "class names intellisense" for svelte components but disabling bad autocompletion is ok as well..
Screenshots
If applicable, add screenshots to help explain your problem.
System (please complete the following information):
Maybe GitHub Actions deploying via tags? Then anyone with write access to the repo has write access to deploy.
Describe the bug
Our project has a component named Script
. When we instantiate that component, VS Code shows dozens of errors from the Svelte lang server. Renaming the component to something like MyScript
before instantiation removes all errors.
To Reproduce
Steps to reproduce the behavior:
Script.svelte
:
<script>
export let title = 'Working Draft';
export let you = 'you';
</script>
<p>A film named {title} starring {you}</p>
App.svelte
:
<script>
import Script from './Script.svelte';
let y = { x: 1, y: 0};
</script>
<h1>Film</h1>
<Script title="Svelte: The Documentary" you="Rich Harris" />
Open in VS Code w/ the Svelte Beta extension active
Observe errors in App.svelte
in "Problems" pane (View -> Problems)
Expected behavior
I would expect the language server to recognize <Script .../>
as a component and not a script tag, especially since the code compiles.
Screenshots
System (please complete the following information):
Describe the bug
when using this syntax on html element:
out:send="{{ key: 'section' }}"
in:receive="{{ key: 'section' }}"
The formatter remove the wrapping quote, which break the code
Is there a way to not add spaces in the below html during formatting?
I need this code to stay like this:
<div>
Test (<span class="color">one</span>)
</div>
It becomes this instead:
<div>
Test (
<span class="color">one</span>
)
</div>
Is your feature request related to a problem? Please describe.
Right now renaming/moving svelte files does not update the imports in other svelte files.
Describe the solution you'd like
Renaming/moving svelte files should update the imports in other svelte files.
Additional context
I dug around the language server protocol a little but found no event that says "file X moved from A to B" or "file X was renamed to Y". Instead, onDidCloseTextDocument
and onDidOpenTextDocument
events fire, and also the onCodeAction
event is invoked with the new file path and a range with start/end of 0. One could infer a file rename/move from these events, if they appear shortly after each other, but I'm not sure if this is a hack or the only possible solution. If someone knows more about this, please comment.
I have
{
"extends": "standard"
}
(which comes from https://github.com/standard/eslint-config-standard#usage) in my .eslintrc.js and I'm wondering why this doesn't work in <script></script> part of my .svelte files.
What rules is this plugin following?
UPDATE:
Reproduction project: https://github.com/frederikhors/svelte3-vscode-eslint
Using this in command line: npx eslint --fix .\src\*
works good, it changes App.svelte and main.js as I want: following standard.js rules.
Is your feature request related to a problem? Please describe.
Implement semantic tokens so theme makers can apply Svelte-specific styling in their themes. (This is a feature since VSCode 1.43)
https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide#theming
Following addition, guidelines/docs for theme makers should be added to the plugin description so they can target these tokens.
Describe the solution you'd like
Sample implementation can be found here, https://github.com/Microsoft/vscode-extension-samples/tree/master/semantic-tokens-sample
Describe alternatives you've considered
Make it a seperate optional plugin instead of integrating into Svelte Beta
.
Hi, this looks like a really interesting project!
Does this project handle TypeScript in .svelte
files currently or just JavaScript at the moment?
If it does handle TypeScript, can it run the TypeScript compiler and output JavaScript on to the file system or is it only meant to be used in Visual Studio?
If it's not yet supported, is handling TypeScript a goal someday and what would be required to compile TypeScript and output it to the file system? I potentially could help in this direction depending what's required. Most likely through testing and providing feedback, but maybe also writing tests or helping with some implementation details depending how much time I end up having
Thanks!
I love to use Atom but svelte package for it, so old, so like is there anyway to talk with the author and make it official package?
It would be better language supporting I guess..
Is there a way to format js with single quotes on save? They revert to double quotes when I format.
It seems like there is a plugin for LSP https://plugins.jetbrains.com/plugin/10209-lsp-support
https://github.com/gtache/intellij-lsp
I tried running the executable /usr/local/bin/svelteserver
but nothing happens, can anyone point me to the right direction? Thanks.
If you go to Svelte on VSCode Market you can see that Github link is leading to /svelte instead of /sveltejs
There are some requests to use the language-server in other IDE environments (#34). We could have all plugins for these IDEs in this repo, but this might get cumbersome. So it would be better to provide the language server as a npm package.
Do we want to do this, and if yes, when?
If yes, what's the package name? (bikeshedding incoming)
In VS code, an each block breaks syntax highlighting for that line and the rest of the file. It appears as a comment (I think due to #
).
Test case (smaller version of https://svelte.dev/tutorial/keyed-each-blocks):
<script>
import Thing from './Thing.svelte';
let things = [
{ id: 1, color: '#0d0887' },
{ id: 2, color: '#6a00a8' }
];
</script>
{#each things as thing}
<Thing current={thing.color}/>
{/each}
Happy to take a stab at fixing this if someone can give me pointers.
The typescript error disappears as soon as I comment out the <script context="module">
:
Maybe related to #100
I noticed that the language server crashes regulary on SveltePlugin
. I investigated a bit and found out that the crash is due to an error inside a preprocessor. That preprocessor tries to load a module which is only present inside my workspace's node_modules, but not inside the language-server's node_modules.
More concrete: svelte-preprocess
crashes inside this function trying to resolve node-sass / sass because I use SCSS inside my style-tags.
What can we do about that? Is there any way to find out what the preprocessors want to load and reroute their import paths to the workspace? Do we need to establish some kind of preprocessor-convention (they listing their dependencies consumable for us)?
Related: Ways to change require paths
Describe the bug
When making event handler (i.e. on:click), the arrow function autocompletion inside seems to be malfunctioning.
To Reproduce
Try typing:
<div class="answer" on:click={() =}
when you do >
it autocomplete the div inside the arrow function, see gif below:
Expected behavior
No autocompletion, let me do the arrow function.
Screenshots
System (please complete the following information):
Describe the bug
Projects using prettier@2
+ prettier-plugin-svelte
for code formatting see different results from running prettier --write
vs svelte-vscode
+ formatOnSave
To Reproduce
<script>
const foo = bar().baz().baf();
</script>
svelte-vscode
formats this as:
<script>
const foo = bar()
.baz()
.baf();
</script>
prettier --write
formats this as
<script>
const foo = bar().baz().baf();
</script>
Expected behaviour
Expect the formatting to be consistent.
Ideally, I would expect svelte-vscode
to use some instance of prettier
installed locally or globally before anything else.
System (please complete the following information):
Additional context
Looks very much like the svelte-vscode
is formatting like prettier@1
Describe the bug
It appears that attempting to subscribe to a store (for example, if you had Readable<Promise<T>>
) in an #await block produces an error in the IDE.
To Reproduce
<script>
import { readable } from 'svelte/store';
const store = readable(Promise.resolve('test'), () => {});
</script>
{#await $store}
<p>loading</p>
{:then data}
{data}
{/await}
Expected behavior
The #await should work and correctly unwrap the store type.
System (please complete the following information):
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.