An open API service indexing awesome lists of open source software.

https://github.com/jaywcjlove/prettier

A Swift code formatting library based on JavaScriptCore and Prettier
https://github.com/jaywcjlove/prettier

formatter prettier swift

Last synced: 9 months ago
JSON representation

A Swift code formatting library based on JavaScriptCore and Prettier

Awesome Lists containing this project

README

          


Using my app is also a way to support me:


VidCrop
Vidwall
Mousio Hint
Mousio
Musicer
Audioer
FileSentinel
FocusCursor
Videoer
KeyClicker
DayBar
Iconed
RightMenu Master
Quick RSS
Quick RSS
Web Serve
Copybook Generator
DevTutor for SwiftUI
RegexMate
Time Passage
Iconize Folder
Textsound Saver
Create Custom Symbols
DevHub
Resume Revise
Palette Genius
Symbol Scribe


Prettier
===

A Swift code formatting library based on JavaScriptCore and [Prettier](https://github.com/prettier/prettier).

## Features

- 🚀 Support for multiple language formatting: JavaScript, TypeScript, CSS, JSON, HTML
- 🎛️ Fully configurable formatting options
- 📦 Built-in Prettier bundle, no external dependencies required
- 🔧 Based on JavaScriptCore, excellent performance
- 🎯 Clean Swift API

## Installation

### Swift Package Manager

Add CodeMirror to your project using Xcode:

1. In Xcode, go to `File` → `Add Package Dependencies...`
2. Enter the repository URL: `https://github.com/jaywcjlove/Prettier.git`
3. Click `Add Package`

Or add it to your `Package.swift` file:

```swift
dependencies: [
.package(url: "https://github.com/jaywcjlove/Prettier.git", from: "1.0.0")
]
```

## Quick Start

```swift
import Prettier

// 1. Create a formatter instance
let formatter = try PrettierFormatter()

// 2. Format code
let uglifiedJS = "const user={name:'John',age:30};function greet(){console.log('Hello '+user.name);}"
let beautifiedJS = try formatter.format(uglifiedJS, parser: .babel)

print(beautifiedJS)
// Output:
// const user = { name: "John", age: 30 };
// function greet() {
// console.log("Hello " + user.name);
// }
```

## Usage

### Basic Usage

```swift
import Prettier

// Create a PrettierFormatter instance
let formatter = try PrettierFormatter()

// Format JavaScript code
let jsCode = "const x={a:1,b:2};"
let formatted = try formatter.format(jsCode, parser: .babel)
print(formatted)
// Output:
// const x = { a: 1, b: 2 };
```

### Formatting Different Types of Code

#### JavaScript/TypeScript

```swift
// JavaScript (using babel parser)
let jsFormatted = try formatter.format("const x={a:1,b:2};", parser: .babel)

// TypeScript
let tsCode = "interface User{name:string;age:number;}"
let tsFormatted = try formatter.format(tsCode, parser: .typescript)

// Flow
let flowCode = "// @flow\ntype User = {name: string, age: number};"
let flowFormatted = try formatter.format(flowCode, parser: .flow)
```

#### CSS/SCSS/Less

```swift
// CSS
let cssCode = "body{margin:0;padding:0;font-family:Arial,sans-serif;}"
let cssFormatted = try formatter.format(cssCode, parser: .css)

// SCSS
let scssCode = "$primary: #333; body { color: $primary; }"
let scssFormatted = try formatter.format(scssCode, parser: .scss)

// Less
let lessCode = "@primary: #333; body { color: @primary; }"
let lessFormatted = try formatter.format(lessCode, parser: .less)
```

#### JSON

```swift
let jsonCode = #"{"name":"John","age":30}"#
let jsonFormatted = try formatter.format(jsonCode, parser: .json)

// JSON5
let json5Code = "{name:'John',age:30,}"
let json5Formatted = try formatter.format(json5Code, parser: .json5)
```

#### HTML/Vue/Angular

```swift
// HTML
let htmlCode = "

Hello World

"
let htmlFormatted = try formatter.format(htmlCode, parser: .html)

// Vue
let vueCode = "

{{ message }}
"
let vueFormatted = try formatter.format(vueCode, parser: .vue)

// Angular
let angularCode = "

{{ item }}
"
let angularFormatted = try formatter.format(angularCode, parser: .angular)
```

#### Markdown/GraphQL/YAML

```swift
// Markdown
let markdownCode = "# Title\n\nSome **bold** text."
let markdownFormatted = try formatter.format(markdownCode, parser: .markdown)

// GraphQL
let graphqlCode = "query{user{name age}}"
let graphqlFormatted = try formatter.format(graphqlCode, parser: .graphql)

// YAML
let yamlCode = "name: John\nage: 30\naddress:\n city: NYC"
let yamlFormatted = try formatter.format(yamlCode, parser: .yaml)
```

### Custom Formatting Options

```swift
let options = PrettierOptions(
printWidth: 100,
tabWidth: 4,
useTabs: false,
semi: false,
singleQuote: true,
quoteProps: .asNeeded,
jsxSingleQuote: false,
trailingComma: .none,
bracketSpacing: true,
bracketSameLine: false,
arrowParens: .avoid,
endOfLine: .lf,
rangeStart: 0,
rangeEnd: Int.max,
requirePragma: false,
insertPragma: false,
proseWrap: .preserve,
htmlWhitespaceSensitivity: .css,
vueIndentScriptAndStyle: false,
singleAttributePerLine: false,
embeddedLanguageFormatting: .auto
)

let formatted = try formatter.format(code, parser: .babel, options: options)
```

### Supported Parsers

```swift
// JavaScript related
.babel // JavaScript (ES6+)
.babelFlow // JavaScript with Flow types
.babelTs // TypeScript via Babel
.flow // Flow
.typescript // TypeScript
.acorn // JavaScript (Acorn parser)
.espree // JavaScript (ESTree parser)
.meriyah // JavaScript (Meriyah parser)

// Stylesheets
.css // CSS
.less // Less
.scss // SCSS/Sass

// Data formats
.json // JSON
.json5 // JSON5
.jsonStringify // JSON (stringify format)
.yaml // YAML

// Markup languages
.html // HTML
.vue // Vue SFC
.angular // Angular templates
.lwc // Lightning Web Components
.markdown // Markdown
.mdx // MDX

// Others
.graphql // GraphQL
.glimmer // Glimmer templates
```

### Formatting Options

- `printWidth`: Maximum characters per line (default: 80)
- `tabWidth`: Tab width (default: 2)
- `useTabs`: Whether to use tabs instead of spaces (default: false)
- `semi`: Whether to add semicolons (default: true)
- `singleQuote`: Whether to use single quotes (default: false)
- `quoteProps`: Object property quote strategy (.asNeeded, .consistent, .preserve)
- `jsxSingleQuote`: Whether to use single quotes in JSX (default: false)
- `trailingComma`: Trailing comma strategy (.none, .es5, .all)
- `bracketSpacing`: Whether to add spaces inside object literal brackets (default: true)
- `bracketSameLine`: Whether to put the > of multi-line JSX elements at the end of the last line (default: false)
- `arrowParens`: Arrow function parentheses strategy (.always, .avoid)
- `endOfLine`: Line ending character (.auto, .lf, .crlf, .cr)
- `rangeStart/rangeEnd`: Formatting range (default: entire file)
- `requirePragma`: Whether to require a format comment at the top of the file (default: false)
- `insertPragma`: Whether to insert a format comment (default: false)
- `proseWrap`: Text wrapping strategy (.always, .never, .preserve)
- `htmlWhitespaceSensitivity`: HTML whitespace sensitivity (.css, .strict, .ignore)
- `vueIndentScriptAndStyle`: Whether to indent script and style tags in Vue files (default: false)
- `singleAttributePerLine`: Whether to put only one HTML attribute per line (default: false)
- `embeddedLanguageFormatting`: Embedded language formatting (.auto, .off)

## Error Handling

```swift
do {
let formatter = try PrettierFormatter()
let formatted = try formatter.format(code, parser: .babel)
print(formatted)
} catch PrettierError.resourceNotFound {
print("prettier.bundle.min.js resource file not found")
} catch PrettierError.jsContextInitializationFailed {
print("JavaScript context initialization failed")
} catch PrettierError.prettierObjectNotFound {
print("Prettier object not found in JavaScript context")
} catch PrettierError.formattingFailed(let message) {
print("Formatting failed: \(message)")
} catch {
print("Other error: \(error)")
}
```

## Error Types

- `PrettierError.resourceNotFound`: prettier.bundle.min.js resource file not found
- `PrettierError.jsContextInitializationFailed`: JavaScript context initialization failed
- `PrettierError.prettierObjectNotFound`: Prettier object not found in JavaScript context
- `PrettierError.formattingFailed(String)`: Formatting failed with detailed error message

## Development

```bash
# Build Prettier JS bundle
cd scripts && npm start
# Run tests
swift test
```

## License

Licensed under the MIT License.