A Swift code formatting library based on JavaScriptCore and Prettier.
- 🚀 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
Add CodeMirror to your project using Xcode:
- In Xcode, go to
File→Add Package Dependencies... - Enter the repository URL:
https://github.com/jaywcjlove/Prettier.git - Click
Add Package
Or add it to your Package.swift file:
dependencies: [
.package(url: "https://github.com/jaywcjlove/Prettier.git", from: "1.0.0")
]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);
// }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 };// 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
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)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
let htmlCode = "<div><p>Hello World</p></div>"
let htmlFormatted = try formatter.format(htmlCode, parser: .html)
// Vue
let vueCode = "<template><div>{{ message }}</div></template>"
let vueFormatted = try formatter.format(vueCode, parser: .vue)
// Angular
let angularCode = "<div *ngFor=\"let item of items\">{{ item }}</div>"
let angularFormatted = try formatter.format(angularCode, parser: .angular)// 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)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)// 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 templatesprintWidth: 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)
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)")
}PrettierError.resourceNotFound: prettier.bundle.min.js resource file not foundPrettierError.jsContextInitializationFailed: JavaScript context initialization failedPrettierError.prettierObjectNotFound: Prettier object not found in JavaScript contextPrettierError.formattingFailed(String): Formatting failed with detailed error message
# Build Prettier JS bundle
cd scripts && npm start
# Run tests
swift testLicensed under the MIT License.