Laravel Breeze with Inertia, React, Eslint, Prettier, Pint and Husky

Lokman Musliu Founder and CEO of Lucky Media
Lokman Musliu

September 12, 2022 · 6 min read

Laravel Breeze with Inertia, React, Eslint, Prettier, Pint and Husky

Now that is quite a title there.

Starting out with building big applications can be tricky, but with the right tools and habits, you can make sure your work goes smoothly. In this guide, we’ll share the methods we’ve developed from working with Laravel Breeze, Inertia, and React, to help you keep your code consistent throughout your project.

Why a consistent codebase matters

Having the same code style is key to a good work environment for making software. It makes your code easier to read and keep up, letting your team find their way around the project more easily. This clearness is very important when you need to find and fix errors, as well as when you’re reviewing pull requests (PRs). In short, having consistent code can cut down on the time it takes to develop and help your team work better together.

Addressing the challenge

One problem you might run into, especially when you focus on building the front end with Inertia and tools like React or Vue, is keeping your styling and coding rules the same. There are lots of resources for setting up front-end projects with tools like ESLint, Prettier, and Husky, but it’s harder to find help for combining these tools in a big, single architecture.

Prerequisites for the tutorial

Before you start the guide, you should have a new Laravel installation ready to use. We'll start from scratch, so you shouldn't have any earlier setups or changes. This makes sure you can follow along without any issues and get the most out of the guide as we create a big, single application that's both effective and stylish.

First, we start by installing Laravel Breeze:

composer require laravel/breeze --dev

Then we have to install the starter kit. For this example, we will go with React.

php artisan breeze:install react

# Now migrate and install
php artisan migrate
npm install && npm run dev

Laravel IDE helper

This amazing package is something we include in every project along with Debugbar. Based on the description of the package, this is what it does:

This package generates helper files that enable your IDE to provide accurate autocompletion. Generation is done based on the files in your project, so they are always up-to-date.

composer require --dev barryvdh/laravel-ide-helper

In the scripts section of your composer.json file, you need to add the following:

{
  "post-update-cmd": [
    "@php artisan vendor:publish --tag=laravel-assets --ansi --force",
    "@php artisan ide-helper:models -N",
    "@php artisan ide-helper:generate",
    "@php artisan ide-helper:eloquent",
    "@php artisan ide-helper:meta"
    ],
}

Pest

Laravel Pest is a testing library for Laravel that makes it easy to write and run tests. It is based on the popular PHPUnit testing library and provides a number of useful features specific to Laravel.

To install, follow their excellent documentation.

Frontend setup

To have everything formatted nicely, we will need to install a few npm packages that will make sure we have a consistent codebase.

npm i -D eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks husky lint-staged prettier pretty-quick

The command above will install the following packages:

  • Eslint ( along with prettier, react, react hooks plugin )

  • Prettier ( used to format our JSX files)

  • Pretty Quick ( Runs prettier on git changed files )

  • Lint Staged ( Runs linters on staged files )

  • Husky ( Ability to have git hooks, run commands on each commit )

Now let's go into detail for each setup.

Eslint

A proper Eslint installation needs a new file in the root dir called .eslintrc.js with the following config.

module.exports = {
  root: true,
  parserOptions: {
    ecmaVersion: 2020, // Use the latest ecmascript standard
    sourceType: 'module', // Allows using import/export statements
    ecmaFeatures: {
      jsx: true, // Enable JSX since we're using React
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  env: {
    browser: true,
    amd: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:prettier/recommended',
  ],
  plugins: ['prettier'],
  rules: {
    'react/jsx-first-prop-new-line': [2, 'multiline'],
    'react/jsx-max-props-per-line': [2, { maximum: 1, when: 'multiline' }],
    'react/jsx-indent-props': [2, 2],
    'react/jsx-closing-bracket-location': [2, 'tag-aligned'],
    'prettier/prettier': [
      'error',
      {},
      {
        usePrettierrc: true,
      },
    ],
    'react/react-in-jsx-scope': 'off',
    'react/prop-types': 'off',
    'no-console': 2,
  },
};

This is our opinionated Eslint config and we won’t cover all the details. Feel free to modify how you see fit based on your project structure.

If you are using VSCode, you might want to include the following script in your Settings.json. Every time you hit save, the code is formatted automatically and the editor won’t scream at you.

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}


Prettier

In order for Prettier to play nice in our project, we have to create a new file in our root dir called .prettierrc

{
  "printWidth": 80,
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "arrowParens": "avoid"
}

The same goes for the Prettier config, it’s opinionated to suit our requirements but feel free to change it if you want a different config.

Pretty Quick

No setup is needed here we run the command from the npm scripts that we will cover later on.

Lint Staged

We need to add the following key at the end of our package.json file to get lint-staged working.

{
  "lint-staged": {
    "*.js": "eslint --cache --fix"
  }
}

The above will run eslint on our staged files before pushing to our origin repo.

Implementing Husky for better code consistency

With the frontend configurations well in hand, we reach the thrilling part of our setup process. Despite our best efforts to establish clear coding standards, individual developer preferences and habits can lead to deviations. Common reasons for such inconsistencies include misconfigured editor settings or simply overlooking established rules. This is where Husky steps in as a game-changer.

Husky enhances our workflow by implementing Git hooks, acting as a vigilant gatekeeper for our codebase. With each new commit attempt, Husky triggers predefined commands to format the code and detect any issues. If these checks reveal problems, the commit is blocked until the issues are resolved. This ensures that nothing short of clean, compliant code makes it into our repository, safeguarding the uniformity and quality of our codebase.

We edit our package.json file and add the following commands to our scripts section.

{
  "scripts": {
    "prepare": "husky install",
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint --fix .",
    "format": "prettier 'resources/{js,jsx}/**/*.{js,jsx}' --write",
    "pre-commit": "npm run format && lint-staged && pretty-quick --staged"
  },
}

Now we can run npm run prepare to make sure husky will install correctly.

P.S make sure you have a git repo or it will fail.

We need to add our pre-commit hook. You can either create it by running a command or manually.

The file pre-commit (without extension) needs to be created under the .husky folder.

Add the following command inside the pre-commit file.

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run pre-commit

This will add a git hook that will call our pre-commit script in our package.json file.

If you followed everything correctly, simply commit all changes to your repo. You should see the following in your terminal.

Terminal Image of a code

P.S. gc "fixed testing" is a shorthand for git add . && git commit "fixed testing"

CI/CD setup

We can’t enforce the rules on everyone or you might skip the Husky setup for certain reasons. In that case, we can use GitHub Workflows to make sure the commands run on each Pull Request.

Here is our GitHub Action that formats the code on Pull Requests:

name: Code Fixes

on:
  pull_request:
    branches: [main]

jobs:
  php-code-styling:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          ref: ${{ github.head_ref }}

      - name: Fix PHP code style issues
        uses: aglipanci/laravel-pint-action@1.0.0

      - name: Cache node modules
        id: cache-npm
        uses: actions/cache@v3
        env:
          cache-name: cache-node-modules
        with:
          # npm cache files are stored in `~/.npm` on Linux/macOS
          path: ~/.npm
          key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-build-${{ env.cache-name }}-
            ${{ runner.os }}-build-
            ${{ runner.os }}-
      - if: ${{ steps.cache-npm.outputs.cache-hit != 'true' }}
        name: List the state of node modules
        continue-on-error: true
        run: npm list

      - name: Install dependencies
        run: npm ci
      - name: Format code
        run: npm run format

      - name: Commit changes
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: Fix styling

The script above will run Laravel Pint to format your PHP code and then it will run our format script to make sure all the frontend components are nicely styled. If there is an error, the Action will fail and the pull request will not complete.

Finishing up

Thanks for following this very long and detailed tutorial. If you feel ready to jump straight to the code, we prepared a demo repo running here.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let’s get in touch.

Lucky Media is proud to be recognized as a leading Laravel Development Agency

Technologies

LaravelReact
Lokman Musliu Founder and CEO of Lucky Media
Lokman Musliu

Founder and CEO of Lucky Media

Stay up-to-date

Be updated with all news, products and tips we share!

Let’s chat

We partner with a limited number of brands each quarter to ensure senior-level attention on every project.

lokman and arlind headshots
Teamwork

Related posts

November 9, 2023

How to scope a Laravel project
Laravel
Business

April 30, 2021

Laravel Breeze with Inertia and React
Laravel
Inertia
React

March 23, 2021

Laravel datatable with Grid.js
Laravel