Oxfmt Practical Tutorial: Make Your Code Formatting Lightning Fast
Learn to use Oxfmt, a code formatting tool 10x faster than Prettier, with this comprehensive tutorial covering installation, configuration, and editor integration.
Oxfmt Practical Tutorial: Make Your Code Formatting Lightning Fast
Have you ever experienced this: running prettier --write "./src/**/*" and watching the file list scroll slowly, with hundreds of files taking tens of seconds or even longer to format?
Today, we’re introducing Oxfmt, which can completely transform this experience. As the formatting tool in the OXC toolchain, it’s not only fast but also highly compatible with Prettier.
What is Code Formatting?
Before diving into Oxfmt, let’s understand the significance of “code formatting”.
Why Format Code?
Look at this code:
// Messy formatted code
const user={name:"John",age:25,email:"test@example.com"};
function getUserInfo( user ){
const{name,age}=user;
return `User ${name}, age ${age}`;
}
After formatting:
// Well-formatted code
const user = { name: "John", age: 25, email: "test@example.com" };
function getUserInfo(user) {
const { name, age } = user;
return `User ${name}, age ${age}`;
}
Benefits of code formatting:
- Improved Readability: Well-organized code is easier to read and understand
- Fewer Conflicts: Unified style reduces arguments during code reviews
- Increased Efficiency: Auto-formatting saves time on manual adjustments
Prettier’s Popularity
Prettier is currently the most popular code formatting tool, used by almost every frontend project. Its features include:
- Convention over Configuration: Provides sensible default formats
- Multi-language Support: JavaScript, TypeScript, CSS, HTML, JSON, etc.
- Rich Ecosystem: Integrates with various editors and toolchains
Oxfmt’s Position
Oxfmt is part of the OXC project, written in Rust, aiming to be a high-performance alternative to Prettier:
- Speed Advantage: 10-30x faster than Prettier
- High Compatibility: Supports Prettier configuration format
- Continuous Evolution: Feature coverage constantly improving
Installing Oxfmt
Option 1: Global Installation
# Using npm
npm install -g oxfmt
# Using yarn
yarn global add oxfmt
# Using pnpm
pnpm add -g oxfmt
Option 2: Project Installation
npm install oxfmt --save-dev
Add scripts in package.json:
{
"scripts": {
"format": "oxfmt \"./src/**/*.{js,jsx,ts,tsx}\" --write",
"format:check": "oxfmt \"./src/**/*.{js,jsx,ts,tsx}\" --check"
}
}
Option 3: Using npx
npx oxfmt "./src/**/*.{js,ts}" --write
Quick Start
Basic Commands
# Format a single file
oxfmt src/main.js --write
# Format multiple files (using glob pattern)
oxfmt "./src/**/*.{js,jsx,ts,tsx}" --write
# Check if formatting matches standards (without modifying files)
oxfmt "./src/**/*.{js,ts}" --check
# Show formatting differences
oxfmt "./src/**/*.js" --diff
Command Line Options
| Option | Description |
|---|---|
--write | Modify files directly |
--check | Only check, don’t modify, returns exit code |
--diff | Show differences before and after formatting |
--config <path> | Specify configuration file path |
Practical: Formatting Your First Project
Let’s walk through it step by step.
Step 1: Create Test File
Create src/example.js:
// Intentionally messy formatting
const config={
debug: true,
api:"https://api.example.com",
timeout:5000
}
function fetchData( endpoint ){
const url = config.api+endpoint
return fetch(url,{timeout:config.timeout})
.then(response=>response.json())
.catch(error=>{
console.error('Error:',error)
throw error
})
}
export{config,fetchData}
Step 2: Run Formatting
oxfmt src/example.js --write
Step 3: View Formatting Result
The formatted code:
// Well-formatted
const config = {
debug: true,
api: "https://api.example.com",
timeout: 5000,
};
function fetchData(endpoint) {
const url = config.api + endpoint;
return fetch(url, { timeout: config.timeout })
.then((response) => response.json())
.catch((error) => {
console.error("Error:", error);
throw error;
});
}
export { config, fetchData };
Step 4: Use —diff to View Differences
oxfmt src/example.js --diff
Example output:
--- src/example.js
+++ src/example.js (formatted)
@@ -1,13 +1,15 @@
-const config={
- debug: true,
- api:"https://api.example.com",
- timeout:5000
+const config = {
+ debug: true,
+ api: "https://api.example.com",
+ timeout: 5000,
}
Configuration File
Oxfmt supports customizing formatting rules through configuration files.
Creating a Configuration File
Create .oxfmtrc or oxfmt.config.js in the project root:
// .oxfmtrc
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "es5",
"printWidth": 80,
"bracketSpacing": true,
"arrowParens": "always"
}
Configuration Options Explained
| Option | Type | Default | Description |
|---|---|---|---|
semi | boolean | true | Whether to add semicolons at end of statements |
singleQuote | boolean | false | Use single or double quotes |
tabWidth | number | 2 | Number of spaces for indentation |
useTabs | boolean | false | Use tabs or spaces for indentation |
trailingComma | string | "es5" | Trailing comma rules |
printWidth | number | 80 | Maximum characters per line |
bracketSpacing | boolean | true | Spaces inside object literal braces |
arrowParens | string | "always" | Arrow function parameter parentheses |
trailingComma Option
// "none" - No trailing commas
const obj = {
a: 1,
b: 2
};
// "es5" - Use where ES5 supports (objects, arrays)
const obj = {
a: 1,
b: 2,
};
// "all" - Use everywhere (including function parameters)
function example(
a,
b,
) {}
arrowParens Option
// "always" - Always use parentheses
const fn = (x) => x * 2;
// "avoid" - Omit parentheses for single parameter
const fn = x => x * 2;
Editor Integration
Auto-formatting in the editor greatly improves development efficiency.
VS Code Configuration
Method 1: Using the Oxc Extension
- Install “Oxc - Oxidation Compiler” extension
- Configure in
.vscode/settings.json:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "oxc.oxc-vscode",
"[javascript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "oxc.oxc-vscode"
}
}
Method 2: Using Command Line + Run on Save
In .vscode/settings.json:
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.format": true
}
}
Add in package.json:
{
"scripts": {
"format": "oxfmt \"./src/**/*.{js,ts,jsx,tsx}\" --write"
}
}
WebStorm / IntelliJ IDEA
- Open Settings → Tools → External Tools
- Add new tool:
- Name:
Oxfmt - Program:
npx - Arguments:
oxfmt "$FilePath$" --write
- Name:
- Set up keyboard shortcut or auto-run on file save
Compatibility with Prettier
Oxfmt aims for high compatibility with Prettier, but some features are still in development.
Supported Features
| Feature | Status |
|---|---|
| JavaScript/TypeScript formatting | ✅ Supported |
| JSX/TSX formatting | ✅ Supported |
| JSON formatting | ✅ Supported |
| Basic configuration options | ✅ Supported |
.prettierrc configuration reading | ✅ Supported |
Features in Development
| Feature | Status |
|---|---|
| CSS/SCSS formatting | 🚧 In Development |
| HTML formatting | 🚧 In Development |
| Markdown formatting | 🚧 In Development |
| Plugin system | 🚧 Planned |
Migration Suggestions
If you’re using Prettier, you can migrate like this:
- Keep Prettier Configuration File
Oxfmt can directly read .prettierrc or prettier.config.js:
// prettier.config.js
module.exports = {
semi: true,
singleQuote: true,
tabWidth: 2,
trailingComma: 'es5',
printWidth: 100,
};
- Progressive Replacement
{
"scripts": {
"format": "oxfmt \"./src/**/*.{js,ts}\" --write",
"format:prettier": "prettier --write \"./src/**/*.{css,html,md}\""
}
}
Use Oxfmt for JS/TS, and Prettier for other file types.
Performance Comparison
Let’s look at the performance difference between Oxfmt and Prettier.
Test Environment
- File count: 200 TypeScript files
- Total code: About 50,000 lines
- Machine: MacBook Pro M1
Test Results
| Tool | First Run Time | Second Run Time |
|---|---|---|
| Prettier | 3.2 seconds | 2.8 seconds |
| Oxfmt | 0.15 seconds | 0.12 seconds |
Oxfmt is about 20x faster than Prettier!
Real-World Impact
In large projects or CI/CD environments, the difference is even more significant:
| Scenario | Prettier | Oxfmt |
|---|---|---|
| pre-commit hook | 10-30 seconds | 0.5-2 seconds |
| CI format check | 1-2 minutes | 3-5 seconds |
| Full project formatting | Several minutes | A few seconds |
Practical Tips
Ignore Specific Files
Create a .oxfmtignore file:
# .oxfmtignore
node_modules/
dist/
build/
*.min.js
*.d.ts
coverage/
Format Specific Ranges
Use glob patterns for precise control:
# Only format component files in src directory
oxfmt "./src/components/**/*.{jsx,tsx}" --write
# Exclude test files
oxfmt "./src/**/*.ts" --ignore "./src/**/*.test.ts" --write
Use with lint-staged
In package.json:
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"oxfmt --write"
]
}
}
Combined with husky for pre-commit auto-formatting:
{
"scripts": {
"prepare": "husky install"
}
}
FAQ
Oxfmt and Prettier Output Differ?
Due to implementation differences, some edge cases may not be completely consistent. You can reduce differences by adjusting configuration.
How to Handle Files Prettier Doesn’t Support?
Keep Prettier as a fallback:
{
"scripts": {
"format": "oxfmt \"./src/**/*.{js,ts,jsx,tsx,json}\" --write && prettier --write \"./src/**/*.{css,scss,html,md}\""
}
}
What Languages Does Oxfmt Support?
Currently supports:
- JavaScript (
.js,.mjs,.cjs) - TypeScript (
.ts,.tsx,.mts,.cts) - JSX (
.jsx) - JSON (
.json)
Summary
This article covered Oxfmt’s core usage:
| Content | Command |
|---|---|
| Format files | oxfmt ./src --write |
| Check format | oxfmt ./src --check |
| View differences | oxfmt ./src --diff |
| Configuration file | .oxfmtrc or oxfmt.config.js |
Oxfmt’s core value: Turning code formatting from “waiting” to “instant”.
Next Steps
Want to learn more about Oxfmt’s configuration options? Visit OXC Documentation - Formatter Section
In the next article, we’ll dive into OXC Parser — exploring the magic of code parsing and understanding how AST works!
💡 Related Reading: