language-tools
language-tools copied to clipboard
prettier-plugin-organize-imports needs some help :)
Hello maintainers, this is in reference to https://github.com/simonhaenisch/prettier-plugin-organize-imports/issues/39 where we are trying to add Svelte support. A couple of us have tried unsuccessfully to understand how you do it here.
Can you help by providing a code sample (or add a Svelte test) that, given the string input of a Svelte file, returns the same thing with imports organized?
There isn't a public API for it. Our code structure is quite different from volar. There isn't a language-service package to be reused. You might have to do more work for it, unfortunately. But I would assume that organize-import might not need as much of the logic we have in the language service host layer. It should not be very difficult.
What we did is:
-
we implement the
readFileof the language service host with a transformation withsvelte2tsx. It also returns sourcemap info for the next step. https://github.com/sveltejs/language-tools/blob/cd784383555f557eea6cb9e30f3eab586c5e1150/packages/language-server/src/plugins/typescript/DocumentSnapshot.ts#L184-L198 Themodeoption we used here is 'ts' by default. It might also be easier for you as it won't needjsxconfigs in the tsconfig, the namespace issvelteHTMLbut it probably won't matter much for your use case.emitOnTemplateErrorshould betrue.accessorsdidn't matter much. -
run the organize-import from the ts language service and sourcemap the result back to the original file. By the start and end of the range. And then apply some logic to fix the indent and the possible sourcemap errors. https://github.com/sveltejs/language-tools/blob/cd784383555f557eea6cb9e30f3eab586c5e1150/packages/language-server/src/plugins/typescript/features/CodeActionsProvider.ts#L114-L151 The indentation part can probably be replaced with a
ts.FormatCodeSettings.baseIndentoption. We didn't do it for some historical reason and also that makes us able to detect existing indent, Which probably isn't needed for a prettier plugin.
As for tests, you could find them here. Setup isn't important for your use case. You can just read the corresponding file and the result text edit. Also as I mentioned earlier the indent might not be super important for a prettier plugin. https://github.com/sveltejs/language-tools/blob/cd784383555f557eea6cb9e30f3eab586c5e1150/packages/language-server/test/plugins/typescript/features/CodeActionsProvider.test.ts#L539-L1117
Hope that helps you. Feel free to ask more if you have some trouble understanding.
Thank you so much!