prettier-plugin-java
Prettier is an opinionated code formatter which forces a certain coding style. It makes the code consistent through an entire project.
This plugin allows the support of Java on Prettier.
The plugin implementation is pretty straightforward as it uses java-parser (thanks to Chevrotain) visitor to traverse the Concrete Syntax Tree and apply the format processing on each node (it uses Prettier API).
Installation
Pre-requirements
Since the plugin is meant to be used with Prettier, you need to install it:
npm install --save-dev --save-exact prettier
or
yarn add prettier --dev --exact
Install plugin
npm install prettier-plugin-java --save-dev
or
yarn add prettier-plugin-java --dev
CLI
If you installed Prettier globally and want to format java code via the CLI, run the following command:
npm install -g prettier-plugin-java
The plugin will be automatically loaded, check here for more.
Usage
CLI
prettier --write MyJavaFile.java
If the plugin is not automatically loaded:
# Example where the plugin is locate in node_modules prettier --write MyJavaFile.java --plugin=./node_modules/prettier-plugin-java
API
const prettier = ;const javaText = `public class HelloWorldExample{ public static void main(String args[]){ System.out.println("Hello World !"); }}`; const formattedText = prettier;
Example of formatted code
Input
Output