Vite4+Vue3+Eslint+Prettier+Stylelint项目配置,学不会你打我!

3,557 阅读9分钟

手把手教学配置 Vite4+Vue3+ts 项目模板众多使用功能

今天 2022年12月16日周五,使用最新的技术手把手教你使用 vite4 构建最实用的vue3 项目。

框架自带功能柜

  • Vite4
  • Vue3
  • Typescript4

编码规范、提交规范相关

  • eslint + pritter + stylelint
  • cz-git
  • husky

框架基础组件

  • alias (不属于这里,但是很快就要用到,先处理)
  • Vue-router4
  • Pinia2
  • Axios
  • Sass or Less
  • Element Plus or Ant-design-vue or Vant4

这部分有切换,后续考虑实现一个脚手架,可以手动选择。

实用功能

  • VueUse
  • icons
  • Windi CSS or Uno CSS or Tailwind CSS
  • 自动导入内部组件:unplugin-auto-import, unplugin-icons
  • 自动导入外部组件:unplugin-vue-components
  • SVG 组件化: vite-svg-loader
  • 移动端px转vw: postcss-px-to-viewport

0.前置环境( Node18.x,pnpm7.14.x )

burtlai@BurtdeMacBook-Pro vue3-ts-template % node -v            
v18.12.1
burtlai@BurtdeMacBook-Pro vue3-ts-template % npm -v             
8.19.2
burtlai@BurtdeMacBook-Pro vue3-ts-template % pnpm -v            
7.14.0

我比较喜欢新技术,使用的是最新的 node 版本,2022-04-19 日发布了 Node V18,已经过去大半年了,是时候大量并广泛地使用了,所以我这里使用了 V18.12.1

我全程使用 pnpm,如果没有安装请先 npm i -g pnpmMac 电脑如果提示没有权限,可以加上 sudo,即 sudo npm i -g pnpm

vite4 已经在 2022-12-09 发布,很新鲜,是时候体验一下了。

image.png

1. 安装基本的项目

pnpm 安装 vue-ts项目命令如下:

 pnpm create vite <project-name> --template vue-ts

我这里创建的项目名为 vue3-ts-template,如下:

pnpm create vite vue3-ts-template --template vue-ts
cd vue3-ts-template
pnpm i
git init
git add .
git commit -m "build: init project"

2. 编码规范、提交规范相关

这里为什么先配置 提交规范,因为这样的话 代码规范 可以被 提交规范 管控,另外一个原因是代码规范篇幅较长,比较繁杂,放到后面吧。

2.1 提交规范,强烈推荐使用 cz-git

查阅了多篇文章,对比了多个工具之后,舍弃了commitlint/commitzen/cz-conventional-changelog等一些列工具,直接上 cz-git

一个中国大佬的开源作品,5星好评!

先安装,再使用,安装是一次性的,使用的话以后只需要 git cz 即可!

2.1.1、 如何安装,只需要 4 步:

参考官网,配置如下

  1. 全局安装 commitizen: npm i -g commitizen
  2. 项目里安装 cz-git: pnpm install -D cz-git
  3. 修改 package.json 增加 config 配置项,配置如下:
{
  "config": {
    "commitizen": {
      "path": "node_modules/cz-git"
    }
  }
}

4)(可选)根目录添加 .commitlintrc.cjs 文件

// .commitlintrc.cjs
/** @type {import('cz-git').UserConfig} */
module.exports = {
  rule: {
    // ...
  },
  prompt: {
    useEmoji: false
    // option...
  }
}

注意:vite3.x 开始生成的项目,package.json 会自动加上 "type": "module",这时根目录的配置文件不能以 .js 结尾,要改为 .cjs,如 .commitlintrc.cjs, .prettierrc.cjs, .eslintrc.cjs

上面的是模板,我的配置如下:

// .commitlintrc.cjs
/** @type {import('cz-git').UserConfig} */
module.exports = {
  rules: {
    // @see: https://commitlint.js.org/#/reference-rules
  },
  prompt: {
    messages: {
      type: '选择你要提交的类型 :',
      scope: '选择一个提交范围(可选):',
      customScope: '请输入自定义的提交范围 :',
      subject: '填写简短精炼的变更描述 :\n',
      body: '填写更加详细的变更描述(可选)。使用 "|" 换行 :\n',
      breaking: '列举非兼容性重大的变更(可选)。使用 "|" 换行 :\n',
      footerPrefixesSelect: '选择关联issue前缀(可选):',
      customFooterPrefix: '输入自定义issue前缀 :',
      footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
      confirmCommit: '是否提交或修改commit ?'
    },
    types: [
      { value: 'feat', name: 'feat:     新增功能 | A new feature' },
      { value: 'fix', name: 'fix:      修复缺陷 | A bug fix' },
      {
        value: 'docs',
        name: 'docs:     文档更新 | Documentation only changes'
      },
      {
        value: 'style',
        name: 'style:    代码格式 | Changes that do not affect the meaning of the code'
      },
      {
        value: 'refactor',
        name: 'refactor: 代码重构 | A code change that neither fixes a bug nor adds a feature'
      },
      {
        value: 'perf',
        name: 'perf:     性能提升 | A code change that improves performance'
      },
      {
        value: 'test',
        name: 'test:     测试相关 | Adding missing tests or correcting existing tests'
      },
      {
        value: 'build',
        name: 'build:    构建相关 | Changes that affect the build system or external dependencies'
      },
      {
        value: 'ci',
        name: 'ci:       持续集成 | Changes to our CI configuration files and scripts'
      },
      { value: 'revert', name: 'revert:   回退代码 | Revert to a commit' },
      {
        value: 'chore',
        name: 'chore:    其他修改 | Other changes that do not modify src or test files'
      }
    ],
    useEmoji: false
  }
}

2.1.2 如何使用,只需要 2 步:

  • git add .
  • git cz

image.png

2.2 Eslint+Prettier+Stylelint

注:本节主要参考 vue3+ts+vite项目中使用eslint+prettier+stylelint+husky指南,并做了些许优化。

2.2.1 Eslint

pnpm i eslint -D
# npx eslint --init
pnpm eslint --init
# npm init @eslint/config
# pnpm init @eslint/config
# 上面4个命令相同,我们用第二个,因为好记,且是 pnpm, 笑😁

配置过程如下

burtlai@BurtdeMacBook-Pro vue3-ts-template % npx eslint --init
You can also run this command directly using 'npm init @eslint/config'.
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · vue
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser, node
✔ What format do you want your config file to be in? · JavaScript
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
✔ Would you like to install them now? · No / Yes
✔ Which package manager do you want to use? · pnpm

注意:Where does your code run? 这一步要把 node 也选上(按空格选中),否则会报错,如下。但是可以通过手动增加 node: true 配置项来解决。

image.png

{
    "env": {
        "browser": true,
        "es2021": true,
+        "node": true
    },
}

image.png

得到的完整的 .eslintrc.cjs 配置如下:

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended'
  ],
  overrides: [],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: ['vue', '@typescript-eslint'],
  rules: {}
}

(先写着,后面配置prettier后还要修改,另外parser也要修改)

package.json 增加 script:

{
    "scripts": {
        "eslint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix"
    }
}

执行 pnpm eslint 命令,提示报错:

image.png 要修改 .eslintrc.cjs 文件的 parser 配置,使用 vue-eslint-parser 才能识别 vue 文件!

-  parser: '@typescript-eslint/parser',
+  parser: 'vue-eslint-parser',
   parserOptions: {
     ecmaVersion: 'latest',
+    parser: '@typescript-eslint/parser',
     sourceType: 'module'
   },

两个parser的区别在于,外面的parser用来解析.vue后缀文件,使得eslint能解析<template>标签中的内容,而parserOptions中的parser,即@typescript-eslint/parser用来解析vue文件中<script>标签中的代码。

eslint 告一段落,下面搞 prettier

2.2.2 Prettier

pnpm add prettier -D

新建 .prettierrc.cjs

module.exports = {
   // 一行的字符数,如果超过会进行换行,默认为80
   printWidth: 80, 
   // 一个tab代表几个空格数,默认为80
   tabWidth: 2, 
   // 是否使用tab进行缩进,默认为false,表示用空格进行缩减
   useTabs: false, 
   // 字符串是否使用单引号,默认为false,使用双引号
   singleQuote: true, 
   // 行位是否使用分号,默认为true
   semi: false, 
   // 是否使用尾逗号,有三个可选值"<none|es5|all>"
   trailingComma: "all", 
   // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
   bracketSpacing: true
}

package.json 增加 script:

{
    "scripts": {
        "format": "prettier --write ./**/*.{html,vue,ts,cjs,json,md}"
    }
}

解决 eslint 和 prettier 的冲突:

pnpm add eslint-config-prettier eslint-plugin-prettier -D

在 .eslintrc.jsonextends的最后添加一个配置

{ 
    extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended',
+    // prettier 必须放在最后面
+    'plugin:prettier/recommended' 
  ],
}

配置好 eslint + prettier 后,可以开始搞 stylelint 了

2.2.3 Stylelint

pnpm add stylelint postcss postcss-less postcss-html stylelint-config-prettier stylelint-config-recommended-less stylelint-config-standard stylelint-config-standard-vue stylelint-less stylelint-order -D

配置 .stylelintrc.cjs:

// .stylelintrc.cjs
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-prettier',
    'stylelint-config-recommended-less',
    'stylelint-config-standard-vue'
  ],
  plugins: ['stylelint-order'],
  // 不同格式的文件指定自定义语法
  overrides: [
    {
      files: ['**/*.(less|css|vue|html)'],
      customSyntax: 'postcss-less'
    },
    {
      files: ['**/*.(html|vue)'],
      customSyntax: 'postcss-html'
    }
  ],
  ignoreFiles: [
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts',
    '**/*.json',
    '**/*.md',
    '**/*.yaml'
  ],
  rules: {
    'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep']
      }
    ],
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['deep']
      }
    ],
    // 指定样式的排序
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'justify-content',
      'align-items',
      'float',
      'clear',
      'overflow',
      'overflow-x',
      'overflow-y',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'width',
      'min-width',
      'max-width',
      'height',
      'min-height',
      'max-height',
      'font-size',
      'font-family',
      'text-align',
      'text-justify',
      'text-indent',
      'text-overflow',
      'text-decoration',
      'white-space',
      'color',
      'background',
      'background-position',
      'background-repeat',
      'background-size',
      'background-color',
      'background-clip',
      'border',
      'border-style',
      'border-width',
      'border-color',
      'border-top-style',
      'border-top-width',
      'border-top-color',
      'border-right-style',
      'border-right-width',
      'border-right-color',
      'border-bottom-style',
      'border-bottom-width',
      'border-bottom-color',
      'border-left-style',
      'border-left-width',
      'border-left-color',
      'border-radius',
      'opacity',
      'filter',
      'list-style',
      'outline',
      'visibility',
      'box-shadow',
      'text-shadow',
      'resize',
      'transition'
    ]
  }
}

这样,样式自动格式化,并且会自动排序,很好!

package.json 中,增加 script:

{
    "script": {
+     "stylelint": "stylelint ./**/*.{css,less,vue,html} --fix",
    }
}

2.2.4 VSCode 配置

增加 .vscode/settings.josn 文件,并写入如下内容:

{
  // 保存的时候自动格式化
  "editor.formatOnSave": true,
  // 配置该项,新建文件时默认就是space:2
  "editor.tabSize": 2,
  // 默认格式化工具选择prettier
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  // 开启自动修复
  "editor.codeActionsOnSave": {
    "source.fixAll": false,
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },
  // stylelint校验的文件格式
  "stylelint.validate": ["css", "less", "vue", "html"]
}

修改 .gitignore 文件,把 .vscode 去掉或者注释掉,这样才能把这个文件加入到版本管理里,其他同事拉代码后才会有这个,大家的编辑环境就一致了!

- .vscode/*
+ # .vscode/*

2.3 配置 husky

虽然上面已经配置好了eslintpreitterstylelint,但是还是存在以下问题。

对于不使用vscode的,或者没有安装eslintpreitterstylelint插件的同学来说,就不能实现在保存的时候自动的去修复与和格式化代码。

pnpm add husky -D

package.json 中,增加 script:

{
    "script": {
+       "prepare": "husky install",
        "prettier": "prettier --write ./**/*.{html,vue,ts,cjs,json,md}",
        "eslint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix",
        "stylelint": "stylelint ./**/*.{css,less,vue,html} --fix",
+       "format": "npm run eslint && npm run stylelint && npm run prettier"
    }
}

该命令会在pnpm install之后运行,这样其他克隆该项目的同学就在装包的时候就会自动执行该命令来安装husky。这里我们就不重新执行pnpm install了,直接执行pnpm prepare,这个时候你会发现多了一个.husky目录。

执行如下脚本,以后提交前(pre-commit)都会进行格式化

pnpm husky add .husky/pre-commit "pnpm format"

image.png

至此,最难的部分都搞定了!

image.png

stylelint 格式化会自动给 css 属性排序,如果你的不生效,看下项目是否作为根目录打开,如果不是可能不生效。

我发现 vue 文件使用 Volar 格式化会有问题,还是使用 prettier 比较好!如下面2图所示

image.png

image.png

最后再次给出我的 .vscode/settings.json 文件:

{
  // 保存的时候自动格式化
  "editor.formatOnSave": true,
  // 配置该项,新建文件时默认就是space:2
  "editor.tabSize": 2,
  // 默认格式化工具选择prettier
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  // 开启自动修复
  "editor.codeActionsOnSave": {
    "source.fixAll": false,
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },
  // stylelint校验的文件格式
  "stylelint.validate": ["css", "less", "vue", "html"],
  "[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

3. 框架基础组件

3.1 @ alias

pnpm add @types/node -D

修改 .vite.config.ts,增加内容如下所示

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
+import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
+  resolve: {
+    alias: {
+      '@': path.resolve(__dirname, './src'), // 把 @ 指向到 src 目录去
+    },
+  },
})

修改 .tsconfig.json,增加内容如下所示

{
  "compilerOptions": {
+    "baseUrl": ".",
+    "paths": {
+      "@/*": ["./src/*"]
+    },
}  }  

后面不写了,网上一大推,给出2个参考文件吧。

Vue3 现已成为新的默认版本,这个开箱即用的Vue3模板它不香吗?

vue3+ts+vite项目中使用eslint+prettier+stylelint+husky指南

结尾

Github 仓库: github.com/vite4-templ…

image.png

欢迎点赞,欢迎使用。