手动搭建vite5+vue3项目。集合ts、vuerouter、prettier、ESlint9等,解决烦人的eslint和prettier配置问题

1,595 阅读7分钟

1、第一步项目初始化

本次搭建采用vite提供模板,运行相关命令生成vite默认提供的项目模板。vite版本V4 本人使用pnpm进行项目管理,未安装请运行 npm install -g pnpm安装pnpm

pnpm create vite my-his --template vue-ts
my-his为项目名称 template后接模板类型 这次采用vue结合ts版本

初始化完成后根据提示install run dev就可看到vite模板项目界面

2、vite基础配置

别名配置

在项目中配置别名提升开发引入配置效率

安装

// 导入 path 的时候提示报错,需要安装 @types/node 类型检测
pnpm add @types/node

配置

// vite.config.ts
import {defineConfig} from 'vite'
import { resolve } from 'path'

import { resolve } from 'path'
export default defineConfig({ 
    resolve: {
        extensions: ['.js', '.json', '.vue', '.ts'],
        alias: {
          '@': resolve(__dirname, 'src'),
          'components': resolve(__dirname, 'src/components'),
          'views': resolve(__dirname, 'src/views'),
          'utils': resolve(__dirname, 'src/utils'),
        }
      }, 
})
// 别名配置需注意:如是ts项目需在tsconfig.app.json中paths相对应添加别名,否则无法通过ts检查

typescripts配置 需要注意ts项目配置别名后还需在ts配置文件中进行配置

// tsconfig.app.json文件中添加相关配置
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
}

开发服务配置

// vite.config.ts中添加
server: {
    host: true, // 可以以IP访问
    port: 8080, // 端口
    open: true, // 自动打开游览器
    cors: true, // 允许跨域
    proxy: {
      '/api': {
        // 这里配置真实的后端环境地址
        target: 'http://aiot',
        changeOrigin: true,
        rewrite: (path) => path.replace('/api/', '/'),
      },
    },
}
// 修改后项目访问端口随之变更才可访问

打包配置

// vite.config.ts中添加
build: {
    // 消除打包大小超过500kb警告
    chunkSizeWarningLimit: 2000,
    // 在生产环境移除console.log
    terserOptions: {
      compress: {
        drop_console: false,
        pure_funcs: ['console.log', 'console.info'],
        drop_debugger: true,
      },
    },
    assetsDir: 'static/assets',
    // 静态资源打包到dist下的不同目录
    rollupOptions: {
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
      },
    },
  },

3、安装UI组件 ant-design-vue

因公司设计风格要求,本次搭建采用 ant-design-vue版本4.0

// 安装ant-design-vue
pnpm add ant-design-vue@next
// vite 按需导入插件
pnpm add unplugin-vue-components -D

此处涉及一个插件,antd-design-vue推荐vite搭建项目使用 unplugin-vue-components。 采用此插件项目中对于UI组件的引用无需频繁imprort等引入操作。

配置

// vite.config.ts文件中做相关修改,此处在ant-design-vue官方文档中提及
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [
        AntDesignVueResolver({
          importStyle: false, // css in js
        }),
      ],
    })
  ],
})

完成上述配置修改可在app.vue文件中添加基础的UI组件在页面中加以验证

<template>
  <div>
    <a-button type="primary">Primary Button</a-button>
  </div>
</template>

补充:import自动引入

前面提到的自动引入针对组件自动引入,Vue、Vue Router、Pinia等也可添加自动引入

安装

pnpm add unplugin-auto-import -D

配置

// vite.config.ts引入
import AutoImport from 'unplugin-auto-import/vite'

plugins: [
    vue(),
    AutoImport({
      imports: ['vue', 'vue-router' ],
    })
]
// 以上配置完成后import { ref } from 'vue'之类导入语句也无需在每个文件内多次声明,主打一个懒惰高效

国际化

// 安装dayjs依赖
pnpm add dayjs

// app.vue中修改
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
const route = useRoute()
const key = computed(() => {
return route.path + Math.random()
})

<template>
  <a-config-provider :locale="zhCN">
    <router-view #="{ Component }" :key="key">
      <component :is="Component" />
    </router-view>
  </a-config-provider>
</template>

4、安装配置less

个人喜好less选择less做css处理插件。ps:以往scss各种版本造成项目各种问题印象不好

安装

pnpm add less

配置

// vite.config.ts文件中做相关修改
export default defineConfig({
  // less支持
  css: {
    preprocessorOptions: {
        less: {
            javascriptEnabled: true,
        },
    },
  },
})

验证

<div class="container">
    <a-button type="primary">Primary Button</a-button>
</div>

<style lang="less" scoped>
.container {
  background: red;
  .ant-btn {
    margin-top: 40px;
  }
}
</style>

注意:原style标签需添加lang="less",对less进行支持

5、vue-router4安装

安装

pnpm add vue-router@4

配置使用

// router/index.ts ----------------创建路由------------------
import {createRouter, createWebHistory} from "vue-router"
import {routes} from "@/router/config"

const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to, from) => {
    console.log(to, from)
    return true
})
export default router

// router/config.ts ----------------路由路径配置文件------------
export const routes = [
    // 路由重定向
    {
        path: '/',
        redirect: '/home',
    },
    {
        path: '/home',
        // component: Home
        component: () => import("@views/home/index.vue")
    },
    {
        path: '/other',
        component: () => import("@views/home/other.vue")
    }
]

// main.ts -----------------使用router--------------------------
import { createApp } from 'vue'
import router from '@/router'
import './style.less'
import App from './App.vue'

const app = createApp(App)
app.use(router)
app.mount('#app')

6、ESlint和prettier

安装

pnpm add @eslint/js eslint eslint-plugin-prettier eslint-plugin-vue globals prettier vite-plugin-eslint -D

新建 .prettierignore文件,内容如下:

dist
*.md
*.html

新建 .prettierrc文件,内容如下:

{
	"semi": false,
	"singleQuote": true,
	"arrowParens": "avoid",
	"useTabs": true,
	"tabWidth": 2,
	"printWidth": 100,
	"bracketSpacing": true,
	"trailingComma": "all",
	"endOfLine": "auto"
}

安装的是最新版本eslint与以往配置有所不同(V9.7.0) 在新版ESlint9版本后,可新建eslint.config.js一个文件可完成所有ESlint的所有配置

import globals from 'globals'
import pluginJs from '@eslint/js'
import pluginVue from 'eslint-plugin-vue'
import prettier from 'eslint-plugin-prettier'

export default [
	{
		files: ['**/*.{js,mjs,cjs,vue}'],
		languageOptions: { globals: globals.browser },
	},
	pluginJs.configs.recommended,
	...pluginVue.configs['flat/essential'],
	{
		plugins: {
			prettier: prettier,
		},
		rules: {
			// 开启这条规则后,会将prettier的校验规则传递给eslint,这样eslint就可以按照prettier的方式来进行代码格式的校验
			'prettier/prettier': 'error',
			'no-var': 'error', // 要求使用 let 或 const 而不是 var
			'no-console': 'off',
			'no-restricted-globals': 'off',
			'no-restricted-syntax': 'off',
			'vue/multi-word-component-names': 'off',
			'no-multiple-empty-lines': ['warn', { max: 1 }],
			'vue/valid-template-root': 'off',
		},
	},
]

配置vite.config.ts

// 引入vite-plugin-eslint
import eslintPlugin from 'vite-plugin-eslint'
// 配置plugins
eslintPlugin({
    include: ['src/**/*.js', 'src/**/*.vue'],
    cache: true,
}),

配置package.json

"lint": "eslint --ignore-pattern .gitignore --fix src",
"format": "prettier .  --write"

注: 配置eslint后自动引入相关也需配置否则eslint检查会报错

// vite.config.ts
plugins: [
    ...,
    AutoImport({
        imports: ['vue', 'vue-router'],
        dts: true,
        eslintrc: {
            enabled: false, // 启用与 Eslint 集成,生成后设置为false,需要重新生成才可打开
            filepath: './.eslintrc-auto-imports.json', // 生成 EsLint 配置文件的路径,需要配置在eslint中避免eslint检查错误
            globalsPropValue: true, // 用于覆盖 globals 属性,
        },
        resolvers: [AntDesignVueResolver()], // 路径解析器列表
    }),
]
// 针对以上自动引入需要配置eslint相关配置用于配合eslint检查

// eslint.config.js
import { readFile } from 'node:fs/promises'

const autoImportFile = new URL('./.eslintrc-auto-imports.json', import.meta.url)
const autoImportGlobals = JSON.parse(await readFile(autoImportFile, 'utf8'))

// 新增,需要进行此处配置自动引入才可通过eslint检查
export default [
    {
        languageOptions: {
            globals: {
                    ...autoImportGlobals.globals,
            },
        },
    }
]

问题:Key "rules": Key "constructor-super": structuredClone is not defined 在完成此代码检查配置后,换了电脑运行项目后产生了此报错。请注意切换node至17版本及 以上(未证实具体最低版本要求,本人切换20.15.1版本后正常)

关于ESlint对ts的配置

接上文配置完成ESlint配置后本人在项目具体的vue代码遇到如下问题

img_v3_02d2_643e4052-8639-41b2-8285-f71cda1488bg.jpg 这是由于eslint.config.js中相关配置及插件不完善,查阅eslint文档及一些文章后解决方法如下

安装

pnpm add vue-eslint-parser @typescript-eslint/parser -D

配置

// eslint.config.js
import commpnParser from 'vue-eslint-parser'
{
    languageOptions: {
        globals: {
            ...autoImportGlobals.globals
        },
        parser: commpnParser,
        parserOptions: {
            ecmaVersion: 'latest',
            sourceType: 'module',
            parser: '@typescript-eslint/parser',
            jsxPragma: 'React',
            ecmaFeatures: {
                jsx: true
            }
        }
    }
}
// 添加以上ESlint对ts的解析帮助配置,相关错误提示消失

7、支持页面 tsx / jsx

安装

pnpm add @vitejs/plugin-vue-jsx @typescript-eslint/parser -D

配置

// 在 vite.config.ts 配置
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
    plugins: [
        vueJsx()
    ]
})

// tsconfig.app.json中配置
{
    "compilerOptions": {
        "jsx": "preserve",
    },
    "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/*.jsx", "auto-imports.d.ts"]
}

8、环境变量

vite可直接在项目根目录新建 .env.环境名 的文件 配置环境变量 新建命名为env的文件夹,分别此文件夹下新建.env.development、.env.test、.env.production三个环境的环境变量配置文件。文件内容VITE_BASEURL = /api,个人可根据项目情况自行修改。

配置

defineConfig({
    envDir: 'env', // 指定环境变量文件所在文件夹
})

// 修改package.json
"scripts": {
    "dev": "vite --mode development",
    "build:development": "vue-tsc -b && vite build --mode development",
    "build:test": "vue-tsc -b && vite build --mode test",
    "build:prod": "vue-tsc -b && vite build --mode production",
})

完成以上配置即可在对应执行环境下通过import.meta.env.VITE_BASEURL获取到对应环境变量

9、提交规范

此处添加husky等代码提交规范,本人使用为husky最新9.1.4版本。相关差异可查看相关文档

安装

pnpm add --save-dev husky

初始化

pnpm exec husky init

此操作后package.json文件会新增一项"prepare": "husky"且文件根目录新增.husky文件夹。

commitlint

添加安装commitlint,commitlint 为当前使用最广泛的git提交规范检验工具,能够帮助在项目开发中,对提交信息的 message 进行规范化校验

pnpm add commitlint @commitlint/cli @commitlint/config-conventional -D

安装完成手动新建.commitlintrc.cjs配置文件

module.exports = {
    extends: ['@commitlint/config-conventional'],
    // 校验规则
    rules: {
        'type-enum': [
            2,
            'always',
            [
                'feat', // 新功能
                'perf', // 优化
                'fix', // 修复bug
                'docs', // 文档
                'style', // 格式
                'build' // 编译相关修改
            ]
        ],
        'type-case': [0],
        'type-empty': [0],
        'scope-empty': [0],
        'scope-case': [0],
        'subject-full-stop': [0, 'never'],
        'subject-case': [0, 'never'],
        'header-max-length': [0, 'always', 72]
    }
}
// 以上规则校验可自行根据习惯要求等进行修改

lint-stated

安装

pnpm add lint-staged -D

配置 在package.json文件中增加以下内容

{
    "scripts": [
        "lint-staged": "lint-staged"
    ],
    "lint-staged": {
        "*.{js,ts,jsx,tsx}": "eslint --fix",
        "*.{ts,tsx,js,jsx,cjs,mjs,vue,css,scss,less,styl,md,html}": "prettier --write"
    },
}

完成以上操作在.husky文件夹下新建pre-commit文件,内容如下:

npx lint-staged

在.husky文件夹下新建commit-msg文件,内容如下:

#!/bin/sh

# shellcheck source=./_/husky.sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit ${1}

完成上述所有步骤后可以进行commit新增提交测试相关校验是否生效,如提交不规范message会产生错误提示commit失败