Open JacobZwang opened 2 years ago
What is your plugin for svelte files? Is it prettier-plugin-svelte
?
A little bit of context about what a Svelte file is:
A Svelte file follows the "Single File Components"-principle (script/style/html in one file) and mostly looks like regular HTML, with some additional micro syntax on top. The JS/TS code goes into a script
tag. Example:
<script>
/** Hi maybe you want to format me with prettier-plugin-jsdoc */
let foo = 'bar';
</script>
<p>Hello {foo}</p>
<style>
p { color: red; }
</style>
I don't know how this plugin works, but maybe you can do a regex-based search for the <script>
tag, extract its content, save the start and end offset, do the regular jsdoc formatting on it, and then replace the content with the new content. Honestly I'm also not sure how Prettier works when there are multiple plugins present - is it possible to tell Prettier to run plugins in order? If so, that would probably be the best solution.
For other languages, this plugin first running original parser and getting an AST object of parsed string, then replacing comment part of them. With formatted comment and in the end returning it to prettier. The main question is: is svelte plugin parser parsing an AST of string?
The Svelte parser does return a Svelte AST, but before parsing it it blanks the contents of the script and css tags, so the AST only contains the HTML part. This is done because the Svelte parser does not handle languages like TypeScript or SCSS, it would throw an error if it came across them. The original text is inside options.originalText
, this is the code for preprocessing (which does the script/style blank) and parsing: https://github.com/sveltejs/prettier-plugin-svelte/blob/master/src/index.ts#L24 . The contents of the style/script(the one that's interesting to you) are then dealt with through Prettier's embed feature, which allows us to use a different printer for part of the content. This happens here: https://github.com/sveltejs/prettier-plugin-svelte/blob/master/src/embed.ts#L130
To summarize: I'm not sure if the approach of using our parser and traversing the AST will work. You would have to do your work before our parser and preprocessor starts doing stuff, and return the output as a string, so that our preprocessor/parser thinks this is how it always looked. I'm not sure if that's possible with the current Prettier plugin API.
What is your plugin for svelte files? Is it
prettier-plugin-svelte
?
Oops, sorry didn't see this response until now. Thanks for being so on top of things! Yes, that's what I'm using. Unfortunately, I'm not an expert in either the prettier or svelte internals so I can't be of much help here.
Would it be possible to get this to work in svelte files? I don't know enough about how prettier extensions work to know if this would be as easy as adding a file type or much more complex. Thanks!