svelte-ast-print - v0.2.3

svelte-ast-print

NPM Version

Print Svelte AST nodes as a string.
A.k.a. parse in reverse.

This is what you need to create codemods - e.g. for migration between Svelte versions syntaxes.

https://xeho91.github.io/svelte-ast-print

This package depends on:

  1. esrap for printing ESTree specification-compliant AST nodes
  2. zimmerframe for walking on the AST nodes

[!WARNING] TypeScript isn't supported, yet.
See & subscribe to progress on issue #86 - Add support for TypeScript.


[!IMPORTANT] It ignores any previous formatting.
The current focus is to be able to write codemods as soon as possible - because right now, there are no alternatives.

If you need to format modified and stringified Svelte AST, use available formatters for Svelte:


[!NOTE] This package is in beta stage.
See Roadmap

  1. Use the package manager of your choice to install this package:

    npm
    npm install svelte-ast-print
    
    yarn
    yarn add svelte-ast-print
    
    pnpm
    pnpm add svelte-ast-print
    
    bun
    bun add svelte-ast-print
    
  2. Incorporate it into your project, for example using Node.js and with the Svelte parse method:

    import fs from "node:fs";

    import { print } from "svelte-ast-print";
    import { parse } from "svelte/compiler";

    const originalSvelteCode = fs.readFileSync("src/App.svelte", "utf-8");
    let svelteAST = parse(originalSvelteCode, { modern: true });
    // 👆 For now, only modern is supported.
    // By default is 'false'.
    // Is it planned to be 'true' from Svelte v6+

    // ...
    // Do some modifications on this AST...
    // e.g. transform `<slot />` to `{@render children()}`
    // ...

    const output = print(svelteAST); // AST is now a stringified code output! 🎉

    fs.writeFileSync("src/App.svelte", output, { encoding: " utf-8" });

[!IMPORTANT] When using parse from svelte, please remember about passing modern: true to options (second argument). This option is only available starting svelte@5
Example:

import { parse } from "svelte/compiler";

parse(code, { modern: true });
// 👆 Don't forget about this

You can omit it from Svelte v6 - source.

Take a look at contributing guide.

This project follows the all-contributors specification. Contributions of any kind are welcome!

💌 to these people:


Mateusz Kadlubowski

💻 🚧 📖 🚇 ⚠️

If you don't have time, but you need this project to work, or resolve an existing issue, consider sponsorship.

Mateusz "xeho91" Kadlubowski

Project License

This project is licensed under the MIT License.