dprint / dprint-plugin-typescript

TypeScript and JavaScript code formatting plugin for dprint.
https://dprint.dev/plugins/typescript
MIT License
258 stars 57 forks source link

Support for Formatting Vue and Svelte Code with `dprint_plugin_typescript::format_text` #640

Open c12i opened 5 months ago

c12i commented 5 months ago

I am using dprint_plugin_typescript::format_text to programmatically format generated JavaScript, TypeScript, and jsx/tsx files from my code generation cli. This approach works well for these file types, but I would also like to format generated .vue and .svelte files using a similar method.

When attempting to format vue code, the dprint_plugin_typescript::format_text function does not work as expected. Here's an example:

use dprint_plugin_typescript::configuration::ConfigurationBuilder;
use dprint_plugin_typescript::format_text;
use std::path::Path;

fn format_code(code: &str, file_name: &str) -> String {
    let config = ConfigurationBuilder::new()
        .line_width(120)
        .indent_width(2)
        .build();
    format_text(Path::new(file_name), code.to_owned(), &config)
        .expect("Failed to format text")
        .expect("Nothing to format")
}

fn main() {
    let vue_code = r#"
    <template>
                <div>{{ message }}</div>
    </template>

    <script>
    export default {
      data() {
        return {
          message: 'Hello, Vue!'
        }
      }
    }
    </script>

    <style>
    div {
      color: red;
    }
    </style>
    "#;

    let formatted_vue_code = format_code(vue_code, "temp.ts");
    println!("Formatted Vue code:\n{}", formatted_vue_code);
}

This results in an error:

Unexpected token `{`. Expected identifier, string literal, numeric literal or [ for the computed key at file:///temp.ts:3:23

                  <div>{{ message }}</div>

Is there a way to extend the functionality of format_text to support vue and svelte files? Or would creating a plugin be a viable solution for this use case?

Any help on this would be highly appreciated.

Additional Information:

Thank you.