Prettier in action
Prettier is a code formatter that helps you maintain consistent code style by automatically formatting your code according to a set of rules.
Here's a simple demo to show Prettier in action.
### Step 1: Install Prettier
First, you need to install Prettier. You can do this using npm (Node Package Manager):
```sh
npm install prettier --save-dev
```
### Step 2: Create a Configuration File
Create a configuration file named `.prettierrc` in your project directory. This file will contain your Prettier settings. Here's an example configuration:
```json
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}
```
### Step 3: Create a JavaScript File
Create a JavaScript file, for example, `app.js`, with the following content:
```javascript
function greet(name) {
console.log("Hello, " + name);
}
greet("World");
```
### Step 4: Run Prettier
Run Prettier on your JavaScript file to format it:
```sh
npx prettier --write app.js
```
### Example Output
After running Prettier, your `app.js` file will be formatted according to the rules specified in your `.prettierrc` file. The formatted code might look like this:
```javascript
function greet(name) {
console.log('Hello, ' + name);
}
greet('World');
```
### Configuration Options
Here are some common configuration options you can include in your `.prettierrc` file:
- **`semi`**: Add semicolons at the end of statements (`true` or `false`).
- **`singleQuote`**: Use single quotes instead of double quotes (`true` or `false`).
- **`tabWidth`**: Specify the number of spaces per indentation level (e.g., `2` or `4`).
- **`trailingComma`**: Add trailing commas where valid in ES5 (e.g., `none`, `es5`, `all`).
Using Prettier makes coding faster and easier by taking care of formatting details, so you can focus on writing code.
Comments
Post a Comment
Write something to CodeWithAbdur!