Registry / testing / typescript-formatter

typescript-formatter

JSON →
library7.2.2jsnpmunverified

typescript-formatter (tsfmt) is a command-line tool designed for formatting TypeScript code. It leverages the TypeScript Compiler Service API for its formatting capabilities, ensuring alignment with TypeScript's own language services. The current stable version is 7.2.2. Its release cadence appears to be moderate, with the last update (v7.2.2) released in February 2023. A key differentiator is its reliance on the official TypeScript language services, aiming for consistent formatting. It also supports reading configuration from `tsconfig.json`, `tslint.json`, `.editorconfig`, `.vscode/settings.json`, and `tsfmt.json`, allowing for highly customizable formatting rules across various project setups. It provides options for formatting files in place, outputting to stdout, or verifying file formats, making it suitable for both local development and CI/CD pipelines.

npm install typescript-formatter
INSTALL
IMPORT
SIG · TYPESCRIPT-FORMATT
T
typescript-formatter
testingjavascriptv7.2.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
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
musl
node 18–226 runs
build_error
glibc
node 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
Debug
Known issues
breakingMajor TypeScript version upgrades can cause `typescript-formatter` to behave unexpectedly or fail, as it relies on the internal TypeScript Compiler Service API which can have breaking changes.
fix
Always ensure your project's `typescript` peer dependency aligns with the version range specified by `typescript-formatter`. Upgrade `typescript-formatter` when updating your `typescript` version to maintain compatibility.
affects: >=1.0.0
gotchaWhen multiple configuration files (e.g., `tsfmt.json`, `tsconfig.json`, `tslint.json`, `.editorconfig`, `.vscode/settings.json`) exist, their settings can override each other, leading to unexpected formatting results.
fix
Use the `--verbose` flag to debug which configuration files are being loaded and applied. Explicitly disable unwanted config sources using flags like `--no-tslint` or `--no-editorconfig` to isolate formatting rules.
affects: >=1.0.0
gotchaThe project appears to be in maintenance mode, with the last significant update in early 2023. While functional, active development might be slower compared to alternatives.
fix
Consider evaluating alternative, more actively maintained formatters like Prettier if rapid updates or extensive new features are critical for your workflow.
affects: <=7.2.2
Errors
Common errors & fixes
sample.ts is not formatted
The content of the specified TypeScript file does not conform to the configured formatting rules.
fix
Run `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.
fix
Install `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.
fix
First, 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.
Upgrade
Version history
7.2.2latest on npm
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.
Agent activity
13 hits · last 30 days
node
12
Resources
typescript-formatter — npm install typescript-formatter · libregistry