vite构建vue3的备忘

文件路由加载

vite-plugin-pages

  1. 追加声明文件到tsconfig.json

    1
    2
    3
    4
    5
    6
    7
    {
    "compilerOptions": {
    "types": [
    "vite-plugin-pages/client"
    ]
    }
    }
  2. 引入动态生成路由

    1
    import routes from "~pages"; // routes: RouteRecordRaw[]

UI组件库加载

unplugin-vue-components

使用unplugin-vue-components引入naive-ui组件库。

1
2
3
4
5
6
7
8
import Components from "unplugin-vue-components/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";

plugins: [
Components({
resolvers: [NaiveUiResolver()],
})
],

Once the setup is done, a components.d.ts will be generated and updates automatically with the type definitions. Feel free to commit it into git or not as you want.

Make sure you also add components.d.ts to your tsconfig.json under includes.

代码格式化

之前一直使用vue-cli(2.x/3.x)进行vue2项目构建,cli集成使用eslint、prettier进行格式化代码。而用vite构建项目时,需要自己手动增加。
比较流行的规范有standardairbnb两种,个人一直比较偏向使用standard。但是在集成时遇到很多细节问题,standard对SFC的style代码部分格式化做的不尽人意,尤其是前置缩进和:前后空格等。而prettier在这一方面一直是佼佼者。

对 eslint、prettier、stylelint做了对比后,最终使用eslint。原因如下

  • stylelint是对css进行格式化的利器,和prettier有所冲突
  • vscode扩展里eslint和prettier也会冲突,prettier提供的eslint-prettier可以进行兼容eslint
  • eslint对typescript支持校验
  • vue官方提供eslint插件eslint-plugin-vue

安装

1
2
3
4
ni -D eslint
ni -D @typescript-eslint/parser @typescript-eslint/eslint-plugin # typescript相关依赖
ni -D prettier eslint-plugin-prettier eslint-config-prettier # prettier相关依赖
ni -D eslint-plugin-vue # vue相关依赖

eslintrc.js配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
"vue/setup-compiler-macros": true,
},
extends: [
"plugin:@typescript-eslint/recommended",
"plugin:vue/vue3-recommended",
"plugin:prettier/recommended",
],
parser: "vue-eslint-parser",
parserOptions: {
ecmaVersion: "latest",
parser: "@typescript-eslint/parser",
sourceType: "module",
},
plugins: ["vue", "@typescript-eslint"],
};

vscode eslint配置

1
2
3
4
5
6
7
8
9
10
11
12
{
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"eslint.validate": [
// "html",
"javascript",
"javascriptreact",
"vue",
"typescript"
]
}

代码提交校验

husky

1
2
3
4
{
"lint-staged": "lint-staged",
"prepare": "husky install" # npm script
}

lint-staged

1
2
3
4
5
6
7
8
{
"lint-staged": {
"*.{js,jsx,vue,ts,tsx}": [
"eslint --fix",
"eslint --ext .js,.jsx,.vue,.ts,.tsx"
]
}
}

将husky目录添加到git忽略文件当中