Prettier Plugin for Rust

raw JSON →
0.1.9 verified Mon Apr 27 auth: no javascript

A prettier plugin for formatting Rust code, version 0.1.9. It provides Prettier-based formatting for Rust files, supporting both code that compiles and code that doesn't (e.g., missing annotations). It fixes common syntax errors like missing semicolons, blocks, and parentheses. The plugin also includes a VSCode extension. It uses the jinx-rust parser. Key differentiators vs rustfmt: ability to format incomplete code, auto-fix common errors, and integration with Prettier ecosystem. Released monthly or so; actively maintained.

error Error: Cannot find module 'prettier-plugin-rust'
cause Module not installed or not resolved correctly in CommonJS environment.
fix
Install the plugin as a devDependency: npm install --save-dev prettier-plugin-rust. Use ES import if in module context.
error Cannot use import statement outside a module
cause The plugin is ESM-only since v0.1.5, but user's Node.js project is not configured as module.
fix
Add "type": "module" to package.json or use dynamic import(). Alternatively, use Prettier's plugin system via .prettierrc.
error Error: No parser could be inferred for file: src/main.rs
cause Prettier may not automatically select the Rust parser; need to specify explicitly.
fix
Set "parser": "rust" in your Prettier config or use a file extension override: { "overrides": { "files": "*.rs", "options": { "parser": "rust" } } }.
breaking Plugin fails if imported via CommonJS require() due to ESM-only exports.
fix Use ES module import or configure Prettier to load the plugin via its plugin system.
gotcha The plugin requires Prettier to be installed as a peer dependency; it does not work standalone.
fix Install prettier as a dependency alongside prettier-plugin-rust.
deprecated Certain Prettier options like trailingComma and embeddedLanguageFormatting are not supported yet.
fix Avoid using those options; they will be ignored or cause errors.
gotcha Cargo workspace layout may not be detected; files outside a recognized Cargo project may not be formatted correctly.
fix Ensure your .rs files are inside a Cargo project or use Prettier's file detection overrides.
npm install prettier-plugin-rust
yarn add prettier-plugin-rust
pnpm add prettier-plugin-rust

Demonstrates formatting Rust code using Prettier's programmatic API with the plugin. Shows parser option 'rust' and plugin path.

const prettier = require('prettier');
const code = `const LEET = 1337\nfn main() {\n  let x = 1 + 2\n}`;
async function formatRust() {
  const result = await prettier.format(code, {
    parser: 'rust',
    plugins: ['./node_modules/prettier-plugin-rust'],
    tabWidth: 4,
    printWidth: 100,
  });
  console.log(result);
}
formatRust().catch(console.error);