vite项目框架搭建

vite项目框架搭建

在这里插入图片描述

1. 使用vite初始化项目

开始 | Vite 官方中文文档 (vitejs.dev)

pnpm create vite
# 依次设置项目名称、选择框架【vue】、选择语言【typescript】
√ Project name: ... vite-project
√ Select a framework: » Vue
√ Select a variant: » TypeScript

2. element-plus安装

安装

pnpm install element-plus

使用(官方推荐-自动导入)

pnpm install -D unplugin-vue-components unplugin-auto-import
  • 然后把下列代码插入到你的 Vite 的配置文件中
// vite.config.ts
import {
    
     defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
    
     ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
    
    
  // ...
  plugins: [
    // ...
    AutoImport({
    
    
      resolvers: [ElementPlusResolver()],
    }),
    Components({
    
    
      resolvers: [ElementPlusResolver()],
    }),
  ],
})
  • 还需要自动导入样式

不导入的话,当使用指令类型组件(ElMessageBox等),会出现没有样式的问题

安装插件:unplugin-element-plus

pnpm add -D unplugin-element-plus

配置vite-config-ts

// vite.config.ts
//import ElementPlus from 'unplugin-element-plus/vite'
//按官网上面的导入会报错,下面的才可以,不清楚为什么
import ElementPlus from "unplugin-element-plus/dist/vite

export default {
    
    
  plugins: [
    ElementPlus({
    
    
      // options
    }),
  ],
}

3. 引入Tailwind CSS

旧版本中文文档(v2.2.16):https://www.tailwindcss.cn/

安装 Tailwind 以及其它依赖项:

pnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest

创建配置文件

生成 tailwind.config.jspostcss.config.js 文件

npx tailwindcss init -p

修改tailwind.config.js,配置模板路径:

/** @type {import('tailwindcss').Config} */
export default {
    
    
  content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
  theme: {
    
    
    extend: {
    
    },
  },
  plugins: [],
}

将Tailwind指令添加到CSS

将Tailwind的每个层的 @tailwind 指令添加到主CSS文件中(根目录style.css)。

/**style.css头部 */
@tailwind base;
@tailwind components;
@tailwind utilities;

确保style.css文件被导入到您的 ./src/main.js 文件中。

// src/main.ts
import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'

createApp(App).mount('#app')

项目中使用

<template>
  <!-- 使用tailwind的flex样式 -->
  <div class="flex">
    <label>测试tailwindCss</label>
    <el-input value="测试tailwindCss的flex属性"></el-input>
    <el-button>测试</el-button>
  </div>
</template>

4. vue-router

TODO: 后面会对这里做优化,加入路由守卫

安装

pnpm add vue-router@4

新建视图文件

新建views文件夹,新建视图Home和About

  • Home.vue:
<script setup lang="ts"></script>
<template>
  <div>home</div>
</template>
<style lang="css" scoped></style>
  • About.vue:
<script setup lang="ts"></script>
<template>
  <div>About</div>
</template>
<style lang="css" scoped></style>

新建路由文件

新建router文件夹,新建router/index.ts和routes.ts

  • routes.ts:
// routes.ts
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
    {
    
     path: '/', name:'home',component: Home },
    {
    
     path: '/about',name:'about', component: About },
]

export default routes
  • index.ts:
import {
    
    createRouter,createWebHashHistory} from 'vue-router'
import routes from './routes'

// 创建路由实例并传递 `routes` 配置
const router = createRouter({
    
    
  // 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes
})

export default router
  • 路由守卫

提为一个单独文件,新建router/guard.ts

import router from './index'

/**前置守卫 */
router.beforeEach((to,from)=>{
    
    
    console.log({
    
    to,from});
    return true;
})
/**后置守卫 */
router.afterEach((to,from)=>{
    
    
    // console.log({to,from});
})
  • src/main.ts中导入,使用router实例
import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 导入router实例
import router from './router/index'
// 路由守卫
import './router/guard'

// 5. 创建并挂载根实例
const app = Vue.createApp({
    
    })
//确保 _use_ 路由实例使
//整个应用支持路由。
app.use(router)
app.mount('#app')

5. 添加Nprogress

可参考:如何在Vue3+TS的项目中使用NProgress进度条 - 掘金 (juejin.cn)

安装

pnpm install nprogress
# 使用typescript还需要安装类型文件
pnpm install -D @types/nprogress

使用

在路由守卫中使用。

guard.ts:

import router from './index'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css';

/**前置守卫 */
router.beforeEach((to,from)=>{
    
    
    console.log({
    
    to,from});
    nprogress.start()
    return true;
})
/**后置守卫 */
router.afterEach((to,from)=>{
    
    
    nprogress.done()
    // console.log({to,from});
})

TODO:优化Nprogress封装

6. Pinia

安装

pnpm add pinia

创建一个 pinia 实例(根 store)

src/main.ts

/** main.ts*/
import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
import './router/guard'
import {
    
    createPinia} from 'pinia'

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

自定义pinia模块

新建src/store;新建store/user.ts

/** user.ts*/
import {
    
    defineStore} from 'pinia'
export const useUserStore = defineStore('user',{
    
    
    state:()=>({
    
    
        name:'zhangqd'
    })
})

页面中使用

app.vue:

<script setup lang="ts">
import {
      
       useUserStore } from "./store/user";
const userStore = useUserStore();
</script>

<template>
  <div>
    姓名:{
   
   { userStore.name }}
  </div>
</template>

7. eslint

  • 初始化安装和配置ESLint
# 初始化
npm init @eslint/config
# 步骤:选择1
? How would you like to use ESLint? … 
  To check syntax only
❯ To check syntax and find problems
  To check syntax, find problems, and enforce code style
# 2
✔ How would you like to use ESLint? · problems
? What type of modules does your project use? … 
❯ JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these
# 3
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
? Which framework does your project use? … 
  React
❯ Vue.js
  None of these
# 4
✔ 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
# 5(使用空格键选中,全部)
✔ 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? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
✔ Browser
✔ Node
# 6
✔ 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
  YAML
  JSON
# 7
✔ 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

# 8
✔ 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? … 
  npm
  yarnpnpm

# 成功
# 1. Installing eslint-plugin-vue@latest, @typescript-eslint/eslint-plugin@latest, @typescript-eslint/parser@latest
# 2. Successfully created .eslintrc.cjs

上面安装的依赖:eslint-plugin-vue、@typescript-eslint/eslint-plugin、@typescript-eslint/parser

  • 自动生成的.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": {
    
    
    }
}
  • 这时打开任一vue文件报错:

Parsing error: '>' expected.eslint,需要修改.eslintrc.cjs:

module.exports = {
    
    
    "env": {
    
    
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        'plugin:vue/vue3-recommended',
        "plugin:@typescript-eslint/recommended"
    ],
    "overrides": [
    ],
    "parser": "vue-eslint-parser",
    "parserOptions": {
    
    
        "parser": "@typescript-eslint/parser",
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    
    
        "vue/multi-word-component-names": "off",
        "@typescript-eslint/no-unused-vars": "warn"
    }
}

8. prettier

安装

# --save-exact:固定版本,不使用^/~
pnpm add -D --save-exact prettier

根目录创建一个空的配置文件.prettierrc.

echo {
    
    }> .prettierrc.json

根目录创建.prettierignore

让Prettier CLI和编辑器知道哪些文件不需要格式化

# 创建
touch .prettierignore

内容:

# 忽略文件:
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

9. 解决Prettier和Eslint冲突

如果您使用ESLint,请安装eslint-config-prettier,以使ESLint和Prettier相互配合。它关闭所有不必要的或可能与Prettier冲突的ESLint规则。Stylelint也有类似的配置:stylelint-config-prettier

安装

pnpm add -D eslint-config-prettier

配置

"prettier" 添加到 .eslintrc.* 文件中的“extends”数组中。确保将其放在最后,以便它有机会覆盖其他配置。

{
    
    
  "extends": [
    //...
    "prettier"
  ]
}

10. husky

提交代码前校验代码格式/提交信息格式。一旦检查不通过,就可以阻止当前的代码提交,避免了不规范的代码和 git 提交出现在项目中。

安装

pnpm add -D husky

启用Git钩子

npx husky install

修改package.json

要在安装后自动启用Git钩子,需要编辑 package.json,在 script中添加以下指令:

// package.json
{
    
    
  "scripts": {
    
    
    "prepare": "husky install"
  }
}

创建pre-commit挂钩

要向钩子添加命令或创建一个新的钩子,请使用 husky add <file> [cmd]

npx husky add .husky/pre-commit "npm lint"

校验提交信息

pnpm add -D @commitlint/cli @commitlint/config-conventional
  • 生成/新建配置文件
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.cjs

或手动新建配置文件(和上面命令等效) commitlint.config.cjs:

module.exports = {
    
    
  extends: ["@commitlint/config-conventional"],
};
  • 添加commit-msg钩子
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
  • 测试
# 测试(如果commlit-msg生效,回报错)
git commit -m '测试commitlint是否生效'
# 报错:
✖   subject may not be empty [subject-empty]type may not be empty [type-empty]
# 修改为正确格式type: subject(注意:feat后的引号一定是英文引号)
git commit -m 'feat: 测试commitlint是否生效'

绕过预先提交和提交msg钩子

如果某次提交想绕过 pre-commitcommit-msg 钩子,可以使用Git -n/--no-verify 选项:

git commit -m "feat: 提交的msg" --no-verify

11.lint-staged

husky代码提交钩子,pre-commit 在提交前,执行 shell,npm run lint,用于校验修正代码, 但缺点是每次提交前会对所有代码校验,用时长。所以需要借助 lint-staged(只校验当前提交的代码)。

安装

pnpm add -D lint-staged

package.json 文件中添加lint-staged设置

{
    
    
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    
    },
  "dependencies": {
    
    },
  "devDependencies": {
    
    },
  "lint-staged": {
    
    
    "*.{js,jsx,ts,tsx,vue}": "eslint --fix",
    "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
  }
}

修改pre-commit钩子

.husky/pre-commit

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm lint-staged

12. axios

安装

pnpm add axios

猜你喜欢

转载自blog.csdn.net/zqd_java/article/details/132794680