iTranslated by AI
Setting up ESLint in an Astro project
eslint-plugin-astro
I've introduced ESLint into my Astro project, so I'm leaving this as a note.
Basically, I'll be proceeding according to the eslint-plugin-astro documentation, which is introduced in the official Astro documentation.
Installing ESLint and Plugins
First, install the necessary packages. We'll install ESLint itself, eslint-plugin-astro, and eslint-plugin-jsx-a11y for accessibility checks.
npm install --save-dev eslint eslint-plugin-astro eslint-plugin-jsx-a11y
Creating the ESLint Configuration File
This time, I'll be using ESLint's Flat Config. Create an eslint.config.js file in the project root and add the necessary configuration.
The final version of eslint.config.js is as follows:
import js from '@eslint/js';
import globals from 'globals';
import eslintPluginAstro from 'eslint-plugin-astro';
import eslintConfigPrettier from 'eslint-config-prettier';
export default [
js.configs.recommended,
eslintConfigPrettier,
...eslintPluginAstro.configs['flat/recommended'],
...eslintPluginAstro.configs['flat/jsx-a11y-recommended'],
{
languageOptions: {
globals: {
...globals.browser,
dataLayer: false,
},
},
},
];
Below are the key points of this configuration file.
Using with Prettier
eslint-config-prettier has been added. This disables ESLint rules that conflict with Prettier.
npm install --save-dev eslint-config-prettier
// ...
import eslintConfigPrettier from 'eslint-config-prettier';
export default [
// ...
eslintConfigPrettier,
// ...
];
Supporting Google Analytics code
In this project, I'm configuring Google Analytics by referring to an article by an Astro maintainer.
Embedding the code generated by Google Analytics will eventually look like this, but it results in an error error 'dataLayer' is not defined no-undef because dataLayer is undefined within it.
<!-- Google Analytics -->
<script
type="text/partytown"
src="https://www.googletagmanager.com/gtag/js?id=G-8ZCMEEKWF9"
></script>
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag() {
window.dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
To solve this, I've added the following description.
{
languageOptions: {
globals: {
dataLayer: false,
},
},
},
References
Discussion