JS Formatter is a lightweight and customizable JavaScript/TypeScript code formatting library. It uses Babel's powerful parser and traversal tools to format code according to user-defined rules.
- Parse JavaScript and TypeScript code using Babel.
- Apply custom formatting rules, including converting quotes, semicolon usage, and more.
- Flexible options for extensibility and integration into various workflows.
- Command-line interface (CLI) support for ease of use.
Install the package via npm:
npm install unique-js-formatter
import formatCode from 'js-formatter';
const inputCode = 'var a = "hello";';
const options = { useSingleQuotes: true };
const formattedCode = formatCode(inputCode, options);
console.log(formattedCode); // Outputs: let a = 'hello';
You can use the CLI to format files:
npx js-formatter <input-file> [options]
For example:
npx js-formatter example.js --useSingleQuotes
The following options are supported:
- useSingleQuotes: Convert double quotes to single quotes in strings. Default is
true
.
- src/: Contains the core implementation of the formatter, including parsing, traversal, and code generation.
- tests/: Unit tests for various components of the library.
- script.js: A script to test the Abstract Syntax Tree (AST) generation and traversal.
We use Jest for testing. To run tests, execute:
npm test
Here is a sample test case:
test('format code', () => {
const input = 'var a = "hello";';
const output = "let a = 'hello';";
expect(formatCode(input, { useSingleQuotes: true })).toBe(output);
});
Contributions are welcome! Please follow these steps:
- Fork the repository.
- Create a feature branch (
git checkout -b feature-name
). - Commit your changes (
git commit -m 'Add feature'
). - Push to the branch (
git push origin feature-name
). - Open a pull request.
- Babel for providing a robust parser and traversal tools.
- The open-source community for inspiring this project.
Aviral Asthana
Feel free to raise issues or feature requests on the GitHub repository!