sveltejs / prettier-plugin-svelte

Format your svelte components using prettier.
MIT License
746 stars 97 forks source link

[feature request] AST to svelte template #211

Open mizchi opened 3 years ago

mizchi commented 3 years ago

Svelte compiler has parser but no code printer. I need code printer for ast to svelte template.

related https://github.com/sveltejs/svelte/issues/5972

How to implementation

I created fork of this repo.

https://github.com/mizchi/svelte-printer

import { printCode } from '@mizchi/svelte-printer';
import { parse } from 'svelte/compiler';

const code = `<script>let x = 1</script>
<button on:click={() => x += 1}>{x}</button>
`;

const parsed = parse(code);
const printed = printCode(ast);
console.log(printed); => code

https://github.com/mizchi/svelte-printer/commit/dc8ddb20709e3cf4e3fb3a913d5ef0117d1f266a

I skipped parse and preprocess to input svelte AST. To generate code I use astring because I can not use snip phase. I did not need formatter in this case.

davidbonnet/astring: 🌳 Tiny and fast JavaScript code generator from an ESTree-compliant AST.

Why

I'm creating Non Programmer's Form from svelte template. This tool needs bi-directional transform.

or other way

I created fork but is there other clean way?

dummdidumm commented 3 years ago

For now there is no clean way to do this simply because this is not something that's built yet. I think for now your idea to reuse this formatting plugin is probably the fastest way to get going.