language-tools icon indicating copy to clipboard operation
language-tools copied to clipboard

prettier-plugin-organize-imports needs some help :)

Open benallfree opened this issue 3 years ago • 2 comments

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?

benallfree avatar Sep 20 '22 11:09 benallfree

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:

  1. we implement the readFile of the language service host with a transformation with svelte2tsx. 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 The mode option we used here is 'ts' by default. It might also be easier for you as it won't need jsx configs in the tsconfig, the namespace is svelteHTML but it probably won't matter much for your use case. emitOnTemplateError should be true. accessors didn't matter much.

  2. 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.baseIndent option. 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.

jasonlyu123 avatar Sep 20 '22 13:09 jasonlyu123

Thank you so much!

benallfree avatar Sep 20 '22 14:09 benallfree