建一个vite模板

1,042 阅读4分钟

初始化项目

这里直接初始化,初始模板采用vue+ts就好了,过程直接看官网 地址

这里简单的列一下步骤:

  1. pnpm create vite,创建的项目名称为template
  2. cd template && pnpm install
  3. pnpm start,启动查看是否正常

VueRouter

  1. 安装包,pnpm add vue-router
  2. src目录下新建一个router目录并创建index.ts文件,并填写
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  { path: '/', name: 'index', component: () => import('views/home/index.vue') },
  { path: '/login', name: 'login', component: () => import('views/login/index.vue') },
  { path: '/:pathMatch(.*)*', name: '404', component: () => import('views/404/index.vue') }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

export default router
  1. 由于views为类型别名,因此在tsconfig.json中配置
{
    "compilerOptions": {
        // ...
        "paths": {
          "views/*": ["./src/views/*"]
        }
    }
}
  1. vite.config.ts中也需要配置一下
import tsConfig from './tsconfig.json'

type Paths = Record<string, string[]>
const getAlias = (paths: Paths) => {
  const alias: Record<string, string> = {}
  const strReg = /.+(?=\/\*)/
  Object.keys(paths).forEach(key => {
    alias[key.match(strReg)[0]] = resolve(__dirname, paths[key][0].match(strReg)[0])
  })

  return alias
}

export default defineConfig({
    // ...
    resolve: {
        alias: getAlias(tsConfig.compilerOptions.paths)
    }
})

在这一步其实可以用一个vite插件解决vite-tsconfig-paths

然后在vite.config.js中配置

// ...
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [tsconfigPaths()],
});

注意,还需要在tsconfig.json中配置一个属性,否则在vue文件内不生效

{
  "compilerOptions": {
    // 就是这一个配置项
    "allowJs": true
  }
}
  1. 入口文件(main.js)注册router

Vuex

  1. 安装包,pnpm add vuex
  2. 在src目录下创建一个store文件夹并创建index.ts文件,并填写
import { createStore, Store } from 'vuex'

export interface RootState {
  count: number
  prefix: string
  name: string
}

const store: Store<RootState> = createStore({
  state () {
    return {
      prefix: 'prefix',
      name: 'name',
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  getters: {
    fullname(state) {
      return state.prefix + state.name
    }
  }
})

export default store
  1. 在入口文件中引入
  2. 测试使用

Pinia

  1. 按照包,pnpm add pinia
  2. src目录下创建piniaStore文件夹并创建index.ts,写入:
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
    const count = ref(0)
    const prefix = ref('prefix')
    const name = ref('name')
    const fullname = computed(() => prefix.value + name.value)

    function increment() {
        count.value++
        prefix.value = 'changePrefix'
    }

    return {
        count,
        fullname,
        increment
    }
})
  1. 在入口文件中导入
import { createApp } from 'vue'
import { createPinia } from 'pinia'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')
  1. 测试效果

官网地址

Tailwindcss

主要步骤看官网就可以了,我简单罗列一下

  1. 安装包,pnpm add tailwindcss postcss autoprefixer -D
  2. 创建配置文件,npx tailwindcss init -p
  3. tailwind.config.js中添加相关代码
module.exports = {
    // ...
    content: [
        './index.html',
        './src/**/*.{vue,js,ts,jsx,tsx}',
    ]
}
  1. 创建src/index.css文件并填入:
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. 在入口文件导入并测试是否生效
  2. 推荐在VSCode中安装插件,用于开发提示,并在配置中设置相关选项
{
    "editor.quickSuggestions": {
        "strings": true
    }
}

Windicss

直接看官网的安装教程就可以了

Eslint+Prettier

在VSCode中需要安装eslint以及prettier插件

  1. 安装包,pnpm add eslint eslint-plugin-vue prettier eslint-config-prettier vue-eslint-parser @typescript-eslint/parser -D
  2. 根目录创建.prettierrc.js,并进行相关配置,配置项可以看官网
module.exports = {
    tabWidth: 4,
    singleQuote: true,
    bracketSameLine: true
}
  1. 根目录创建.eslintrc.js,并配置
module.exports = {
    env: {
        node: true
    },
    parser: 'vue-eslint-parser',
    parserOptions: {
        parser: '@typescript-eslint/parser',
        sourceType: 'module',
    },
    extends: [
        'eslint:recommended',
        'plugin:vue/vue3-recommended', // 推荐的vue3校验规则
        'prettier'
    ]
}
  1. 为了eslint报错能更明显的体现(在浏览器中),可以安装vite-plugin-eslint,然后在vite.config.ts中配置:
// ...
import eslintPlugin from 'vite-plugin-eslint'

export default defineConfig({
  // ...
  plugins: [eslintPlugin()]
})

不过有一个问题:项目初始启动的时候要保证没有eslint报错,不然启动后即使修复了也没用,解决措施是解决后需要重新启动

如果不想在浏览器中报错也可以用另一个插件@nabla/vite-plugin-eslint,报错信息会显示在控制台中

  1. 自动修复功能,在VSCode的用户配置中配置相关选项
{
    "[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "eslint.validate": ["typescript", "vue", "javascript"],
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "editor.formatOnSave": true
}
  1. 当然也可以在package.json中配置相应的修复选项
{
    "scripts": {
        "eslint": "eslint",
        "eslint:lint": "eslint --fix",
        "prettier": "prettier -w ./src/**/*.{js,ts,vue,css,less}"
    }
}

相关链接地址

Vue-TSC

在vue中除了用eslint和prettier校验外,还可以加上vue-tsc,主要用于vue文件中的ts类型检查

  1. 安装,pnpm add vue-tsc -D
  2. package.json中配置
{
    "scripts": {
        "type-check": "vue-tsc --noEmit"
    }
}

这个Vue+TS模板貌似自带会安装相应的包

husky

  1. 安装pnpm add husky @commitlint/config-conventional @commitlint/cli lint-staged -D
  2. package.json中配置,并执行pnpm prepare
{
    "scripts": {
        "prepare": "husky install"
    }
}
  1. 根目录创建commitlint.config.js以及lint-staged.config.js,分别写入
// commitlint.config.js
module.exports = {
    extends: [
        "@commitlint/config-conventional"
    ]
};
// lint-staged.config.js
module.exports = {
    "./src/**/*.{ts,vue,js}": [
        "pnpm test",
        "git add ."
    ]
}
  1. 执行npx husky add .husky/pre-commit "npx --no-install lint-staged"以及npx husky add .husky/commit-msg "npx --no-install commitlint --edit \$1",查看是否在.husky文件夹下出现相应的文件

  2. package.json配置相应选项

   "scripts": {
        "test": "pnpm prettier && pnpm eslint:lint && pnpm type-check"
    }

总结

以上就是需要用到的工具了,当然还有Stylelint这种与CSS校验和格式化相关的工具以及unplugin-vue-components这种按需导入组件相关的工具,这里暂时先不一一列举了,有需要用到再补充