Keeping your code properly formatted can be time-consuming, but automating it makes things so much easier.
With Prettier and GitHub Actions, you can ensure that your code formatting is consistent without any manual effort.
In this step-by-step guide, let’s show you how to set up automated code formatting with a quick demo.
Steps to follow:
1. If you haven't installed Prettier yet, add it to your project with 'npm install --save-dev prettier'.
2. In your repository, create a new directory named '.github/workflows' for GitHub Actions if it doesn't already exist.
3. Create a new YAML file for the workflow, such as 'format.yml', in the .github/workflows directory.
4. Open format.yml and add the following content to set up the workflow:
‘name: Format Code with Prettier
on:
push:
branches:
- master #Change to your default branch
pull request:
branches:
- master #Change to your default branch
jobs:
format:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14' # Change to your desired Node.js version
- name: Install dependencies
run: npm install
- name: Run Prettier
run: npx prettier --check . #Check if files are formatted’.
5. Save the file, then commit and push it to your repository.
6. To stage the changes, use the command: 'git add .'
7. To commit the changes with a descriptive message, use 'git commit -m "commit message"'.
8. Finally, push the changes to the remote repository by running 'git push origin <branch-name>', replacing <branch-name> with the name of your branch.
9. Now, whenever you push to the branch or open a pull request, GitHub Actions will automatically run Prettier to check your code.
This setup keeps your code formatting consistent and helps maintain quality across your project.
That's it!
This is how you can automate code formatting with Prettier using GitHub Actions.
Automating code formatting with Prettier and GitHub Actions not only saves time but also helps you maintain a clean and consistent codebase.
Now that you’ve set it up, you can focus on writing code while GitHub takes care of the formatting for you.
Still have questions?
Send an email to archana@leadwalnut.com, OR
Book a FREE consultation with an expert developer here.