Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
format
✓ import { format } from 'typescript-formatter';
✗ const { format } = require('typescript-formatter');
While primarily a CLI tool, `format` provides programmatic access to format a single TypeScript code string. CommonJS `require` might work in older Node.js contexts, but ESM `import` is preferred for modern TypeScript projects.
processFiles
✓ import { processFiles } from 'typescript-formatter';
✗ const processFiles = require('typescript-formatter').processFiles;
Used for programmatic processing and formatting of multiple files, mirroring the CLI behavior. This function typically takes a list of file paths and options.
FormatOptions
✓ import { FormatOptions } from 'typescript-formatter';
Type import for configuring the detailed formatting behavior when using the programmatic `format` or `processFiles` functions. This type defines properties such as indent size, tab style, and space insertion rules, reflecting the options available via `tsfmt.json`.
This quickstart demonstrates how to programmatically format a TypeScript file using `typescript-formatter`'s `format` function, including configuring specific formatting options.
import { format, FormatOptions } from 'typescript-formatter';
import * as fs from 'fs';
import * as path from 'path';
async function runFormatterExample() {
const sampleFilePath = path.join(process.cwd(), 'sample.ts');
const initialContent = `class Sample {hello(word="world"){return "Hello, "+word;}}`;
// Create a dummy TypeScript file
await fs.promises.writeFile(sampleFilePath, initialContent, 'utf-8');
console.log('Original content created:\n', initialContent);
const options: FormatOptions = {
// These options correspond to settings found in tsfmt.json or editorconfig
baseIndentSize: 0,
indentSize: 2,
tabSize: 2,
convertTabsToSpaces: true,
newLineCharacter: '\n',
insertSpaceAfterCommaDelimiter: true,
insertSpaceAfterSemicolonInForStatements: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
insertSpaceAfterKeywordsInControlFlowStatements: true,
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
insertSpaceAfterTypeAssertion: false
};
try {
// Format the content of the file programmatically
const formattedResult = await format(sampleFilePath, initialContent, options);
console.log('\nFormatted content:\n', formattedResult.formatted.trim());
// Optionally, write the formatted content back to the file
// await fs.promises.writeFile(sampleFilePath, formattedResult.formatted, 'utf-8');
// console.log(`Formatted and replaced ${sampleFilePath}`);
} catch (error) {
console.error('Formatting failed:', error);
} finally {
// Clean up the dummy file
await fs.promises.unlink(sampleFilePath);
console.log(`\nCleaned up ${sampleFilePath}`);
}
}
runFormatterExample().catch(console.error);
tsfmt --version
Errors
Common errors & fixes
sample.ts is not formatted
The content of the specified TypeScript file does not conform to the configured formatting rules.
fixRun `tsfmt -r <file>` to automatically format and replace the file, or modify your code/configuration to meet the expected format.
Cannot find module 'typescript'
The `typescript` peer dependency is missing or cannot be resolved by the package manager.
fixInstall `typescript` as a direct dependency in your project: `npm install typescript` or `yarn add typescript`. Ensure the installed version satisfies the peer dependency range of `typescript-formatter`.
TypeError: [tsfmt] Formatting failed
An error occurred internally during the formatting process, often due to syntax errors in the input TypeScript code or an incompatibility with the TypeScript language service version.
fixFirst, check the TypeScript file for any syntax errors. If the file is valid, ensure your `typescript` peer dependency is within the compatible range for `typescript-formatter` and consider upgrading `typescript-formatter` to its latest version.
Audit
Dependencies
typescriptrequiredRequired for parsing and formatting TypeScript code; different versions may lead to different formatting results or errors due to changes in the TypeScript Compiler Service API.