[апрель 2024] Настройка проекта AstroJS: VS Code, Prettier, ESlint, Stylelint, Tailwind CSS, PostCSS, минификация файлов

от автора

Changelog находится в конце статьи. Последнее обновление — 21 апреля 2024.

Собрала все файлы в репозиторий: https://github.com/teinett/astro-dot-files/

Настраиваем Visual Studio Code для работы с AstroJS

Устанавливаем плагины VS Code:

Создаем проект

AstroJS 3.x работает на Node 18.14.1 и старше.

1. Устанавливаем AstroJS

npm create astro@latest 

После установки проверяем — запускаем локально:

npm run dev 

Если проект запустился, то можем его посмотреть в браузере: http://localhost:4321.

Останавливаем проект: CTRL + C.

2. Отключаем телеметрию

npm run astro telemetry disable 

Настраиваем проект

1. Настраиваем Typescript — добавляем пути для файлов

AstroJS 3.0 поддерживает Typescript 5.х.

Редактируем файл tsconfig.json:

{   "extends": "astro/tsconfigs/strict",   "compilerOptions": {     "baseUrl": ".",     "paths": {       "@/*": ["./src/*"]     }   } } 

2. Настраиваем EditorConfig

Создаем в корне проекта файл .editorconfig:

root = true  [*] indent_style = space indent_size = 4 end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true charset = utf-8  [{*.json,*.yml}] indent_size = 2  [*.yaml] indent_style = space  [*.md] trim_trailing_whitespace = false 

Настраиваем автоматическую проверку на соблюдение правил редактора.

Внимание! Может не работать при каких-то особых настройках окружения: начинает проверять файлы в папке node_modules. Если вы с таким сталкиваетесь, пропускайте этот шаг.

Устанавливаем линтер:

npm install --save-dev editorconfig-checker 

Добавляем в файл package.json команду для проверки EditorConfig:

… "scripts": { …     "editorconfig": "editorconfig-checker -exclude \"**/node_modules/**\"", …   }, … 

Проверяем, работает ли:

npm run editorconfig 

3. Настраиваем версию node

Вариант 1. Создаем в корне проекта файл .nvmrc:

18 

Вариант 2. В файл package.json добавляем код:

… "engines": {     "node": "18"   }, … 

4. Настраиваем Browserlist

Вариант 1. Создаем в корне проекта файл .browserlistrc:

defaults last 2 version not dead 

Вариант 2. В файл package.json добавляем код:

"browserslist": [     "last 2 version",     "not dead"   ], 

5. Добавляем проверку типов от AstroJS

Добавляем в файл package.json команду для линтера:

… "scripts": { …     "check": "astro check", …   }, … 

Проверяем работу линтера:

npm run check 

6. Добавляем интеграцию с Tailwind CSS

npx astro add tailwind 

В корне проекта создаем файл tailwind.config.cjs, если он не создался автоматически:

module.exports = {     content: ["./src/**/*.{js,ts,jsx,tsx,astro}"],     darkMode: "class",     theme: {},     plugins: [], }; 

Создаем файл со стилями для проекта src/styles/global.css — добавляем в самое начало:

@tailwind base; @tailwind components; @tailwind utilities; 

Файл global.css нужно будет подключить в блоке head в шаблоне Layout.astro.

7. Добавляем Prettier для AstroJS и Tailwind CSS

npm install --save-dev prettier prettier-plugin-astro  

Создаем в корне проекта файл .prettierignore — исключаем форматирование указанных файлов и папок:

.astro/ node_modules/ package-lock.json dist/ 

Создаем в корне проекта файл .prettierrc.mjs с настройками для Prettier:

/** @type {import("prettier").Config} */ export default {     plugins: ['prettier-plugin-astro'],     overrides: [         {             files: '*.astro',             options: {                 parser: 'astro',             },         },     ], };  

Если в проекте используем Tailwind CSS:

npm install --save-dev prettier-plugin-tailwindcss   

Редактируем файл .prettierrc.mjs:

 /** @type {import("prettier").Config} */ export default {     plugins: ['prettier-plugin-astro', 'prettier-plugin-tailwindcss' ], /* Должен быть последним в списке */,     overrides: [         {             files: '*.astro',             options: {                 parser: 'astro',             },         },     ], };  

8. Добавляем ESLint — линтер для JavaScript и JSX

npm install --save-dev eslint eslint-plugin-astro eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin 

Создаем в корне проект файл .eslintrc.yml:

env:   browser: true   node: true   es6: true extends:   - eslint:recommended   - plugin:astro/recommended   - plugin:@typescript-eslint/recommended parser: "@typescript-eslint/parser" plugins:   - "@typescript-eslint" parserOptions:   ecmaVersion: 2022   sourceType: module   extraFileExtensions:     - ".astro" overrides:   - files: "*.astro"     parser: astro-eslint-parser     parserOptions:       parser: "@typescript-eslint/parser"       extraFileExtensions: [".astro"] 

Добавляем в файл package.json команду для линтера:

… "scripts": { …     "lintjs": "eslint . --fix", …   }, … 

Проверяем работу линтера:

npm run lintjs 

9. Добавляем Stylelint — линтер для CSS

Устанавливаем Stylelint и его конфиги:

npm install --save-dev stylelint stylelint-config-html stylelint-config-standard postcss-html 

Дополнительно можно установить плагин stylelint-order для упорядочивания селекторов:

npm install --save-dev stylelint-order 

Используем конфиг stylelint-config-html — он позволяет парсить файлы HTML, XML, Vue, Svelte, Astro.

Создаем в корне проекта файл .stylelintrc.yml:

extends:   - stylelint-config-standard   - stylelint-config-html plugins:   - stylelint-order rules:   order/properties-order:     …  

Пример правил для упорядочивания селекторов: Pepelsbey.dev

Если в проекте используется TailwindCSS, добавляем правила для него:

# .stylelint.yml extends:   - stylelint-config-standard   - stylelint-config-html plugins:   - stylelint-order rules:   at-rule-no-unknown:     - true     - ignoreAtRules:         - tailwind         - apply         - variants         - responsive         - screen   declaration-block-trailing-semicolon: null   no-descending-specificity: null   order/properties-order:     ... 

Добавляем в файл package.json команду для линтера c автоисправлением ошибок, где это возможно:

… "scripts": { …     "lintcss": "stylelint \"src/**/*.{css,astro}\" --fix", …   }, … 

Проверяем работу линтера:

npm run lintcss 

10. Настройка VSCode для ESlint, Stylelint и Prettier

В корне проекта создаем папку .vscode и файлы:

  • .vscode/extensions.json — возможно, уже создан автоматически:

{   "recommendations": ["astro-build.astro-vscode"],   "unwantedRecommendations": [] }  
  • .vscode/launch.json — возможно, уже создан автоматически:

{   "version": "0.2.0",   "configurations": [     {       "command": "./node_modules/.bin/astro dev",       "name": "Development server",       "request": "launch",       "type": "node-terminal"     }   ] }  
  • .vscode/settings.json:

{   "eslint.validate": [     "javascript",     "javascriptreact",     "astro", // Enable .astro     "typescript", // Enable .ts     "typescriptreact" // Enable .tsx   ],   "stylelint.validate": [     "css",     // ↓ Add "html" language.     "html",     // ↓ Add "vue" language.     "vue",     // ↓ Add "svelte" language.     "svelte",     // ↓ Add "astro" language.     "astro"   ],   "prettier.documentSelectors": ["**/*.astro"],   "[astro]": {     "editor.defaultFormatter": "esbenp.prettier-vscode"   } } 

Если в проекте используется TailwindCSS, то файл .vscode/settings.json:

{   "eslint.validate": [     "javascript",     "javascriptreact",     "astro", // Enable .astro     "typescript", // Enable .ts     "typescriptreact" // Enable .tsx   ],   "css.customData": [".vscode/tailwind.json"],   "stylelint.validate": [     "css",     // ↓ Add "html" language.     "html",     // ↓ Add "vue" language.     "vue",     // ↓ Add "svelte" language.     "svelte",     // ↓ Add "astro" language.     "astro"   ],   "prettier.documentSelectors": ["**/*.astro"],   "[astro]": {     "editor.defaultFormatter": "esbenp.prettier-vscode"   } }  

Дополнительно создаем файл .vscode/tailwind.json (решение проблемы Stylelint Unknown at rule @apply css(unknownAtRules)):

{   "version": 1.1,   "atDirectives": [     {       "name": "@tailwind",       "description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",       "references": [         {           "name": "Tailwind Documentation",           "url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"         }       ]     },     {       "name": "@apply",       "description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.",       "references": [         {           "name": "Tailwind Documentation",           "url": "https://tailwindcss.com/docs/functions-and-directives#apply"         }       ]     },     {       "name": "@responsive",       "description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n  .alert {\n    background-color: #E53E3E;\n  }\n}\n```\n",       "references": [         {           "name": "Tailwind Documentation",           "url": "https://tailwindcss.com/docs/functions-and-directives#responsive"         }       ]     },     {       "name": "@screen",       "description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n  /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n  /* ... */\n}\n```\n",       "references": [         {           "name": "Tailwind Documentation",           "url": "https://tailwindcss.com/docs/functions-and-directives#screen"         }       ]     },     {       "name": "@variants",       "description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n   .btn-brand {\n    background-color: #3182CE;\n  }\n}\n```\n",       "references": [         {           "name": "Tailwind Documentation",           "url": "https://tailwindcss.com/docs/functions-and-directives#variants"         }       ]     }   ] }  

11. Настройка общей команды тестов для ESlint и Stylelint

Добавляем в файл package.json команду для проверки всеми линтерами:

… "scripts": { …     "test": "npm run lintcss && npm run lintjs && npm run check", …   }, … 

Если запускается editorconfig-checker, то общая команда для тестов:

… "scripts": { …     "test": "npm run editorconfig && npm run lintcss && npm run lintjs && npm run check", …   }, … 

Проверяем команду:

npm run test 

12. Настройка PostCSS

Официальная инструкция.

AstroJS основан на Vite, и PostCSS уже включен по умолчанию.

Мы уже создали конфиг Browserlist — этот конфиг будет использовать PostCSS для понимания поддерживаемых браузеров.

Установим плагины:

  • Autoprefixer

  • PostCSS Preset Env

  • CSSnano

npm install --save-dev autoprefixer postcss-preset-env cssnano 

Создадим конфиг для PostCSS — файл postcss.config.js в корне сайта:

import autoprefixer from 'autoprefixer'; import postcssPresetEnv from 'postcss-preset-env'; import cssnano from 'cssnano';  const settings = {     plugins: [         autoprefixer(),         postcssPresetEnv({ stage: 1 }),         cssnano({ preset: 'default' }),     ], };  export default settings;  

13. Удаляем неиспользованные стили

Пакет: astro-purgecss

Он сработает на этапе build процесса.

Устанавливаем пакет:

npx astro add astro-purgecss 

Настройки в astro.config.mjs:

import { defineConfig } from "astro/config"; import purgecss from "astro-purgecss";   export default defineConfig({ // ... integrations: [         purgecss({             variables: true,              // for Astro view transitions             keyframes: false,              // for Astro view transitions             safelist: {                 greedy: [                     /*astro*/                 ],             },              // for SSR             content: [                 process.cwd() + "/src/**/*.{astro,vue,jsx,tsx,css}", // Watching astro and vue sources             ],         }),         ...     ], }); 

14. Минификация файлов

Минифицируем сгенерированные во время build процесса файлы.

Установим пакет astro-compress:

npm install --save-dev @playform/compress.

Добавим конфигурацию в файл astro.config.mjs:

import { defineConfig } from "astro/config"; import Compress from "@playform/compress";  export default defineConfig({     integrations: [          ...         Compress({             // CSS: false,             // HTML: false,             Image: false,             // JavaScript: false,             SVG: false,         }), // should be last in the list     ], });  

NOTE! Compress() должен идти последним в списке всех интеграций.

В настройках Compress() можно указать, какие типы файлов не минифицировать (выключить работу плагинов по минификации полностью). В коде выше я буду минифицировать CSS, HTML и JS, а картинки трогать не буду.

Заключение

Мы подготовили проект AstroJS к активной разработке.

Если планируется работа с git-репозиторием, то рекомендую добавить husky и инструкции для тестирования перед заливкой кода в git.

Итоговый файл package.json:

{   "name": "learn-astro",   "type": "module",   "version": "0.0.1",   "scripts": {     "dev": "astro dev",     "start": "astro dev",     "build": "astro build",     "preview": "astro preview",     "astro": "astro",     "editorconfig": "editorconfig-checker",     "lintjs": "eslint . --fix",     "lintcss": "stylelint \"src/**/*.{css,astro}\" --fix",     "check": "astro check",     "test": "npm run editorconfig && npm run lintcss && npm run lintjs && npm run check"   },   "dependencies": {     "astro": "^3.0.5"   },   "devDependencies": {     "@astrojs/check": "^0.3.3",     "@typescript-eslint/parser": "^6.4.0",     "@playform/compress": "^0.0.3",     "astro-purgecss": "^4.1.0",     "autoprefixer": "^10.4.15",     "cssnano": "^6.0.1",     "editorconfig-checker": "^5.1.1",     "eslint": "^8.47.0",     "eslint-plugin-astro": "^0.28.0",     "eslint-plugin-jsx-a11y": "^6.7.1",     "postcss-html": "^1.5.0",     "postcss-preset-env": "^9.1.1",     "prettier": "^3.0.2",     "prettier-plugin-astro": "^0.11.1",     "purgecss": "^5.0.0",     "stylelint": "^15.10.2",     "stylelint-config-html": "^1.1.0",     "stylelint-config-standard": "^34.0.0",     "stylelint-order": "^6.0.3",     "typescript": "^5.3.3"   } }  

Структура проекта:

/ ├── .vscode/ │   ├── extensions.json │   ├── launch.json │   └── settings.svg ├── node_modules/ │   └── папки и файлы ├── public/ │   └── папки и файлы ├── src/ │   └── папки и файлы ├── .browserlistrc ├── .editorconfig ├── .eslintrc.yml ├── .gitignore ├── .nvmrc ├── .prettierignore ├── .prettierrc.mjs ├── .stylelintrc.yml ├── astro.config.mjs ├── package-lock.json ├── package.json ├── postcss.config.js ├── README.md └── tsconfig.json 

Changelog статьи

UPDATE 21 августа 2023. Исправлен конфиг для Prettier, команда для запуска Stylelint (ранее проверяла все папки, а не только src), добавлена инфа про PostCSS

UPDATE 1 сентября. Обновлено для AstroJS 3.x.

UPDATE 14 ноября. Добавлен конфиг Stylelint для TailwindCSS.

UPDATE 17 декабря. Добавила инфу про минификацию файлов html, js, css.

UPDATE 27 декабря. Исправила settings.json для vscode: теперь он работает с Prettier для .astro файлов корректно.

UPDATE 18 апреля 2024. Пакет astro-compress стал @playform/compress

UPDATE 21 апреля 2024. Добавила пакет astro-purgecss для удаления неиспользованных стилей.


ссылка на оригинал статьи https://habr.com/ru/articles/754878/