Это руководство о том, как настроить новый проект Vue 3 с вышеупомянутым техническим стеком, а также некоторыми дополнениями, которые действительно могут помочь в части DX (Developer Experience).
Рассмотрим такие вещи, как:
- Editorconfig
- ESLint
- Husky и lint-staged
- Алиасы путей
- Настройка режима отладки
- Статическая проверка template с помощью vue-tsc
- Добавление директивы Tailwind в CSS
Создание рабочей среды
Для начала создаём новый проект (заменяем <project-name> на название создаваемой папки):
npm create vite@latest <project-name> -- --template vue-ts
Параметр --template vue-ts указывает, что будет создан проект на vuejs с уже настроенным typescript
Переходим в созданную папку:
cd <project-name>
И устанавливаем зависимости:
npm i
Настройка Editorconfig
root = true
[*]
indent_style = tab
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.min.*]
indent_style = ignore
trim_trailing_whitespace = false
insert_final_newline = ignore
[*.{md,txt}]
indent_style = space
indent_size = 4
trim_trailing_whitespace = false
[Makefile]
indent_style = tab
[CHANGELOG.md]
indent_size = false
Дополнительная настройка для VS CODE
Для автоматической правки кода в vs code добавляем расширение в список рекомендуемых:
{
"recommendations": [
// ....
"EditorConfig.EditorConfig",
]
}
Настройка ESLint
npm i -D eslint eslint-plugin-vue eslint-plugin-import@latest @vue/eslint-config-typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin vue-eslint-parser vue-tsc@latest
{
"root": true,
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"plugin:vue/vue3-recommended",
"eslint:recommended",
"@vue/typescript/recommended"
],
"parser": "vue-eslint-parser",
"parserOptions": {
"ecmaVersion": "latest",
"parser": {
"ts": "@typescript-eslint/parser",
"js": "espree",
"<template>": "espree"
},
"sourceType": "module"
},
"plugins": [ "import" ],
"ignorePatterns": [ "dist/**/*", "node_modules/**/*" ],
"rules": {
"indent": "off",
"semi": ["error", "always"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"import/order": ["error", {
"groups": [ "builtin", "external", "internal", "parent", "sibling", "index" ],
"newlines-between": "never",
"alphabetize": { "order": "asc" }
}],
"no-useless-escape": "off",
"vue/no-unused-vars": "error",
"vue/no-v-html": "off",
"vue/html-indent": [ "error", "tab" ],
"vue/component-name-in-template-casing": ["error", "kebab-case", { "registeredComponentsOnly": false, "ignores": [] }],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/indent": [ "error", "tab" ]
}
}
Теперь можем добавить в package.json скрипт для линтинга:
"scripts": {
"lint:script": "eslint --ext .ts,vue --ignore-path .gitignore ."
}
Данный скрипт будет только проверять без фикса ошибок, если нужно автоматически исправить ошибки, то скрипт можно запустить так
npm run lint:script -- --fix
Дополнительная настройка для VS CODE
Для автоматической форматирования кода в vs code добавляем расширение в список рекомендуемых:
{
"recommendations": [
// ....
"dbaeumer.vscode-eslint",
]
}
Чтобы отформатировать файл при сохранении используем следующую настройку:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"typescript",
"vue"
],
"eslint.options": {
"ignorePath": ".gitignore"
}
}
Настройка husky и lint-staged
Перед коммитов давайте запустим статическую проверку, чтобы убедиться, что вы не зафиксируете код содержащий ошибки.
npm i -D husky lint-staged
Добавляем следующее в package.json.
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,vue}": "eslint --fix"
}
}
Это приведет к тому, что ESLint будет запускаться и проверять все файлы перед каждым коммитом, и если будет найдена ошибка, то коммит будет отменён.
Настройка Stylelint
npm i -D stylelint stylelint-config-standard stylelint-config-standard-scss stylelint-config-html @stylistic/stylelint-plugin
Ниже приведен конфиг с рекомендуемыми правами, если нужно оставить правила по умолчанию, то можно убрать rules
/** @type {import('stylelint').Config} */
export default {
extends: ['stylelint-config-standard', 'stylelint-config-standard-scss', 'stylelint-config-html/vue'],
plugins: ['@stylistic/stylelint-plugin'],
// defaultSeverity: 'warning', // правило для вывода сообщений ввиде варнингов, для постепенного ввода в проект stylelint
rules: {
'@stylistic/color-hex-case': ['lower'],
'@stylistic/indentation': [2],
'@stylistic/no-empty-first-line': [true],
'@stylistic/string-quotes': ['double'],
'alpha-value-notation': ['number'],
'at-rule-empty-line-before': ['always', { except: ['after-same-name'], ignore: ['after-comment'] }],
'at-rule-no-unknown': [null],
'color-function-alias-notation': [null],
'color-function-notation': ['legacy'],
'comment-empty-line-before': [null],
'custom-property-empty-line-before': [null],
'custom-property-pattern': [null],
'declaration-block-no-redundant-longhand-properties': [true, { ignoreShorthands: ['inset'] }],
'declaration-no-important': [null],
'font-family-name-quotes': ['always-unless-keyword'],
'no-descending-specificity': [null],
'no-empty-source': [null],
'property-no-vendor-prefix': [null],
'rule-empty-line-before': ['always'],
'scss/at-else-empty-line-before': [null],
'scss/at-mixin-parentheses-space-before': [null],
'scss/at-rule-no-unknown': [true],
'scss/no-global-function-names': [null],
'selector-class-pattern': [null],
'selector-id-pattern': [null],
'selector-max-id': [2],
'selector-no-qualifying-type': [true, { ignore: ['attribute', 'class', 'id'] }],
'selector-pseudo-class-no-unknown': [true, { ignorePseudoClasses: ['deep'] }],
'value-keyword-case': ['lower', { ignoreFunctions: ['v-bind'] }],
},
};
Отредактируем package.json - добавим команды и lint-staged.
{
"scripts": {
"lint:style": "stylelint src/**/*.{css,scss,vue}"
},
"lint-staged": {
"*.{ts,tsx}": "eslint --fix",
"*.{css,scss,vue}": "stylelint --fix",
"*": "prettier -w -u"
}
}
Дополнительная настройка для VS CODE
Для автоматической форматирования кода в vs code добавляем расширение в список рекомендуемых:
{
"recommendations": [
// ....
"stylelint.vscode-stylelint",
]
}
Настройка алиасов путей
Импорт модуля по умолчанию является относительным, но вы хотите установить псевдоним, чтобы всегда ссылаться на один и тот же корень.
npm i -D @types/node
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "src")
}
},
plugins: [vue()]
});
Также изменим tsconfig.json.
{
"compilerOptions": {
//...
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
Теперь при импорте можно использовать псевдоним для пути:
<script setup lang="ts">
import HelloWorld from '@/components/HelloWorld.vue'
</script>
Настройка режима отладки
Добавляем файл .vscode/launch.json:
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "debug",
"type": "chrome",
"request": "launch",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/src"
}
]
}
Запускаем приложение через npm run dev. Затем запускаем режим отладки. Откроется браузер хром в режиме дебага.
Теперь ставим в файле точки остановки и начинаем debug.
Статическая проверка template с помощью vue-tsc
Вы можете статически проверять теги шаблона с помощью vue-tsc.
Он устанавливается при создании шаблона. Однако, начиная с @vue/runtime-dom@3.1.4, он не работает, если для параметра skipLibCheck в tsconfig.json не задано значение true.
{
"compilerOptions": {
//...
"skipLibCheck": true
},
}
{
"scripts": {
//...
"lint:markup": "vue-tsc --noEmit",
}
}
Рекомендуется запускать статические проверки в CI, а не перед фиксацией, поскольку статические проверки могут занимать довольно много времени по мере увеличения количества файлов Vue.
Добавление Tailwind CSS
Установка
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Настройка путей к шаблонам
Добавляем пути ко всем файлам шаблонов в файл tailwind.config.cjs.
module.exports = {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Добавление директивы Tailwind в CSS
Добавляем директивы @tailwind для каждого слоя Tailwind в файл ./src/style.css.
@tailwind base;
@tailwind components;
@tailwind utilities;
