Vite project framework construction

Vite project framework construction

Insert image description here

1. Initialize the project using vite

Start | Vite official Chinese documentation (vitejs.dev)

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

2. element-plus installation

Install

pnpm install element-plus

Use (official recommendation - automatic import)

pnpm install -D unplugin-vue-components unplugin-auto-import
  • Then insert the following code into your Viteconfiguration file
// 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()],
    }),
  ],
})
  • You also need to automatically import styles

If you do not import it, there will be a problem of no style when using instruction type components (ElMessageBox, etc.)

Install plugin: unplugin-element-plus

pnpm add -D unplugin-element-plus

Configurationvite-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. Introduce Tailwind CSS

Old version of Chinese documentation (v2.2.16): https://www.tailwindcss.cn/

Install Tailwind and other dependencies:

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

Create configuration file

Generate tailwind.config.jsand postcss.config.jsfiles

npx tailwindcss init -p

Modify tailwind.config.jsand configure the template path:

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

Add Tailwind directive to CSS

Add directives for each layer of Tailwind @tailwindto the main CSS file (root directory style.css).

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

Make sure style.cssthe file is imported into your ./src/main.jsfiles.

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

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

used in projects

<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: We will optimize this later and add routing guards.

Install

pnpm add vue-router@4

Create a new view file

Create a new views folder, create new views Home and 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>

Create a new routing file

Create a new router folder, new router/index.ts and 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
  • route guard

As a separate file, create a new 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});
})
  • Import in src/main.ts and use router instance
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. Add Nprogress

For reference: How to use NProgress progress bar in Vue3+TS project - Nuggets (juejin.cn)

Install

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

use

Used in route guards.

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: Optimize Nprogress packaging

6. Pineapple

Install

pnpm add pinia

Create a pinia instance (root 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')

Custom pinia module

new src/store; newstore/user.ts

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

Used in the page

app.vue:

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

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

7. eslint

  • Initial installation and configuration of 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

Dependencies installed above: eslint-plugin-vue , @typescript-eslint/eslint-plugin, @typescript-eslint/parser

  • Automatically generated .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": {
    
    
    }
}
  • At this time, opening any vue file reports an error:

Parsing error: '>' expected.eslint, need to modify .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

Install

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

Create an empty configuration file .prettierrc in the root directory.

echo {
    
    }> .prettierrc.json

Root directory creation.prettierignore

Let the Prettier CLI and editor know which files do not need to be formatted

# 创建
touch .prettierignore

content:

# 忽略文件:
# 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. Resolve conflicts between Prettier and Eslint

If you use ESLint, install eslint-config-prettier so that ESLint and Prettier work with each other. It turns off all ESLint rules that are unnecessary or may conflict with Prettier. Stylelint also has a similar configuration: stylelint-config-prettier

Install

pnpm add -D eslint-config-prettier

Configuration

Add "prettier"to .eslintrc.*the "extends" array in the file. Make sure to place it 最后so it has a chance to override other configurations.

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

10. husky

Verify the code format/submission information format before submitting the code. Once the check fails, the current code submission can be prevented, preventing irregular code and git submissions from appearing in the project.

Install

pnpm add -D husky

Enable Git hooks

npx husky install

Modify package.json

To automatically enable Git hooks after installation, you need to edit package.jsonand scriptadd the following directive in:

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

Create pre-commit hook

To add a command to a hook or create a new hook, usehusky add <file> [cmd]

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

Verify submission information

pnpm add -D @commitlint/cli @commitlint/config-conventional
  • Generate/new configuration file
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.cjs

Or manually create a new configuration file (equivalent to the above command) commitlint.config.cjs:

module.exports = {
    
    
  extends: ["@commitlint/config-conventional"],
};
  • Add commit-msghook
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
  • test
# 测试(如果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是否生效'

Bypass pre-commit and commit msg hooks

pre-commitIf you want to bypass the and hooks for a certain commit commit-msg, you can use the Git -n/--no-verifyoption:

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

11.lint-staged

Husky code submission hook, pre-commit, executes shell and npm run lint before submission, which is used to verify and correct the code. However, the disadvantage is that all codes will be verified before each submission, which takes a long time. So you need to use lint-staged (only verify the currently submitted code).

Install

pnpm add -D lint-staged

package.jsonAdd lint-staged settings to the file

{
    
    
  "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"
  }
}

Modify pre-commit hook

.husky/pre-commit

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

pnpm lint-staged

12. axios

Install

pnpm add axios

Guess you like

Origin blog.csdn.net/zqd_java/article/details/132794680