Setting Up ESLint and Prettier in Astro

Introduction

I enjoy using automation tools for error checking and formatting in projects. Using ESLint and Prettier makes the code more consistent and error-free, and additionally adds TypeScript checks and VSCode hints.

Packages

Here are the names and purposes of the packages to be installed. I chose to use TypeScript with Airbnb style configurations, but you can decide on settings that suit you better.

Install Packages

Run the following command in your project location to install all the aforementioned packages: npm install --save-dev @typescript-eslint/parser eslint eslint-config-airbnb-base eslint-config-prettier eslint-plugin-astro eslint-plugin-import eslint-plugin-jsx-a11y prettier prettier-plugin-astro

Configure Packages

Create a file named eslintrc.cjs and place it in the root of your project:

module.exports = {
extends: ['airbnb-base', 'plugin:astro/recommended', 'plugin:astro/jsx-a11y-recommended', 'prettier'],
// ...
overrides: [
{
files: ['*.astro'],
parser: 'astro-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
extraFileExtensions: ['.astro'],
},
rules: {},
},
],
};

Create a file named prettierrc.cjs and place it in the root of your project, setting the appropriate style:

module.exports = {
trailingComma: 'all',
tabWidth: 2,
semi: true,
singleQuote: true,
printWidth: 120,
bracketSpacing: true,
};

Create a file named settings.json and place it in the .vscode folder in the root of your project. This will notify VSCode to check what types of files to validate when using ESLint as a Formatter:

{
"eslint.validate": ["javascript", "javascriptreact", "astro", "typescript", "typescriptreact"]
}

Finally, you can add some NPM Script🔗 so that when you want to manually run ESLint or Prettier checks, you can execute npm run lint or npm run prettier. Add the following two lines in your package.json:

"scripts": {
// ...
"lint": "eslint src/**/*.{js,astro}",
"prettier": "prettier src/**/*.{js,astro}"
}

Additionally, if you are using Alias🔗, you can install the eslint-import-resolver-alias package. This way, when you use Alias paths, ESLint will recognize them without throwing errors.

settings: {
'import/resolver': {
alias: {
map: [['@', './src']],
extensions: ['.astro', '.ts', '.tsx', '.js', '.jsx', '.json', '.vue'],
},
},
},

This setup allows you to use @ to represent the src folder, removing the need to write complex paths based on file relative locations!

<!-- 😎 -->
import Card from '@/components/Card.astro';
<!-- 😫 -->
import Card from '../../components/Card.astro'

Conclusion

With the above configurations, the entire project is now well-organized and provides useful hints. If you have any questions, you can refer to the Commit🔗 example from my own project or leave a comment below.