Clang Format Node Wrapper
clang-format-node is a Node.js wrapper that provides programmatic access to the LLVM project's `clang-format` and `git-clang-format` native binaries. The current stable version is 3.0.2, bundling LLVM clang-format version 22.1.3. This package securely builds and bundles these native binaries directly from official LLVM source code, eliminating third-party binary dependencies and offering full GitHub Actions Attestation and npm Build Provenances for enhanced supply chain security. It also includes separate packages within its monorepo, `clang-format-git` for standalone Git integration without Python, and `clang-format-git-python` for the original Python script wrapper. Release cycles typically align with new LLVM clang-format versions, ensuring access to the latest formatting capabilities and bug fixes. It is inspired by `angular/clang-format` but aims for a more streamlined and secure integration into Node.js and npm workflows.
Common errors
-
Error: spawn clang-format ENOENT
cause The underlying `clang-format` native binary could not be found or executed by Node.js, often due to an unsupported platform/architecture, corrupted installation, or restrictive execution environment.fixEnsure your OS and CPU architecture are supported by `clang-format-node`. Check the integrity of your `node_modules` and try reinstalling the package. If in a container or CI, verify permissions for binary execution. Consult the official documentation's 'Supported' section for compatible environments. -
SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES Module `import` syntax in a CommonJS (`require`) environment. `clang-format-node` v3+ is primarily designed for ESM.fixConfigure your project to use ES Modules (e.g., by adding `"type": "module"` to your `package.json`) or use a transpiler (like TypeScript or Babel) to convert ESM syntax to CommonJS if you must target a CJS environment. -
TypeError: The 'format' function requires a string input.
cause The `format` function was invoked with a non-string value (e.g., `null`, `undefined`, an object, or an array) for the `code` argument.fixAlways pass a string representing the code to be formatted as the first argument to the `format` function. Implement input validation before calling the formatter.
Warnings
- breaking Version 3.0.0 introduced a significant breaking change by upgrading the bundled LLVM `clang-format` binary from `llvmorg-21.1.8` to `llvmorg-22.1.1`. This upgrade may result in subtle changes to how code is formatted, potentially causing diffs in previously formatted files, and requires Node.js >= 16. Projects relying on specific formatting behavior should thoroughly review their configurations and output after upgrading.
- gotcha This package bundles native `clang-format` binaries tailored for specific OS platforms and architectures. While comprehensive support is offered, specific environments (e.g., custom Linux distributions, sandboxed CI environments, or unsupported architectures) might encounter issues with binary execution or path resolution. This can lead to `ENOENT` errors or unexpected behavior if the binary cannot be located or run.
- gotcha The `clang-format-node` project is a monorepo containing three distinct packages: `clang-format-node` (the core formatter), `clang-format-git` (git integration without Python), and `clang-format-git-python` (git integration with Python). Installing the incorrect package can lead to missing functionality or unnecessary dependencies.
- gotcha The package officially supports Node.js version 16 and above. While it might function on slightly older versions due to not relying on the very latest Node.js features, using it with Node.js versions below 16 is not officially tested or supported and may lead to installation failures or runtime errors due to engine compatibility checks.
Install
-
npm install clang-format-node -
yarn add clang-format-node -
pnpm add clang-format-node
Imports
- format
const { format } = require('clang-format-node');import { format } from 'clang-format-node'; - execClangFormat
import execClangFormat from 'clang-format-node';
import { execClangFormat } from 'clang-format-node'; - getClangFormatVersion
import { getClangFormatVersion } from 'clang-format-node'; - FormatOptions
import type { FormatOptions } from 'clang-format-node';
Quickstart
import { format } from 'clang-format-node';
async function applyFormatting() {
const code = `#include <iostream>\n\nint main() { std::cout << "Hello, World!" << std::endl; return 0; }\n`;
try {
// Formats the C++ code string using the 'Google' style
// 'fallbackStyle' ensures a default is used if 'style' isn't recognized or available.
const formattedCode = await format(code, {
style: 'Google',
fallbackStyle: 'LLVM'
});
console.log('Original Code:\n', code);
console.log('Formatted Code (Google Style):\n', formattedCode);
// Example of formatting with a different style (e.g., 'Mozilla')
const anotherFormattedCode = await format(code, {
style: 'Mozilla',
fallbackStyle: 'LLVM'
});
console.log('Formatted Code (Mozilla Style):\n', anotherFormattedCode);
} catch (error) {
console.error('Failed to format code:', error);
// Specific error handling for clang-format issues
if (error instanceof Error && error.message.includes('clang-format failed')) {
console.error('The clang-format binary returned an error. Check input or style options.');
}
}
}
applyFormatting();