TypeScript Formatter (tsfmt)
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.
Common errors
-
sample.ts is not formatted
cause 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'
cause 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
cause 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.
Warnings
- breaking Major 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.
- gotcha When 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.
- gotcha The 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.
Install
-
npm install typescript-formatter -
yarn add typescript-formatter -
pnpm add typescript-formatter
Imports
- format
const { format } = require('typescript-formatter');import { format } from 'typescript-formatter'; - processFiles
const processFiles = require('typescript-formatter').processFiles;import { processFiles } from 'typescript-formatter'; - FormatOptions
import { FormatOptions } from 'typescript-formatter';
Quickstart
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);