项目构建
vite2
vue3
ts
Vuex
VueRouter
Element-plus
axios
vscode
-
- 首选项>设置>扩展>eslint>启用format
- vue、ts文档中 空白处右键 使用…格式化文档
- 配置默认格式化程序
- 选择ESLint
- 首选项>设置>扩展>eslint>启用format
#初始化项目
npm init vite@latest
#or
yarn create vite
#Need to install the following packages:
# create-vite@latest
#Ok to proceed? (y) y
#√ Project name: ... shop-admin
#√ Select a framework: » vue
#√ Select a variant: » vue-ts
#Scaffolding project in E:\vue_project\shop-admin...
#Done. Now run:
#进入项目文件夹
cd shop-admin
#使用vscode打开项目
code .
#打开终端 安装依赖包
npm install
npm run dev
#or
yarn
yarn dev
-----------------------------------------------
1.安装eslint代码检测插件
npm install eslint --save-dev
# or
yarn add eslint --dev
2.初始化ESlint配置
npm init @eslint/config
# or
yarn create @eslint/config
-----------------------------------------------
? 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
-----------------------------------------------
? What type of modules does your project use? ...
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these
-----------------------------------------------
? Which framework does your project use? ...
React
> Vue.js
None of these
-----------------------------------------------
? Does your project use TypeScript? » No / Yes Yes
-----------------------------------------------
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
Node
-----------------------------------------------
? How would you like to define a style for your project? ...
> Use a popular style guide
Answer questions about your style
-----------------------------------------------
? Which style guide do you want to follow? ...
Airbnb: https://github.com/airbnb/javascript
> Standard: https://github.com/standard/standard
Google: https://github.com/google/eslint-config-google
XO: https://github.com/xojs/eslint-config-xo
-----------------------------------------------
? What format do you want your config file to be in? ...
> JavaScript
YAML
JSON
-----------------------------------------------
? The style guide "standard" requires eslint@^7.12.1. You are currently using eslint@8.13.0.
Do you want to downgrade? » No / Yes Yes
-----------------------------------------------
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^7.12.1 eslint-plugin-import@^2.22.1 eslint-plugin-node@^11.1.0 eslint-plugin-promise@^4.2.1 || ^5.0.0 @typescript-eslint/parser@latest
? Would you like to install them now with npm? » No / Yes Yes
4.npm script 中添加验证脚本package.json
中
"scripts": {
...
"lint": "eslint ./src/**/*.{js,jsx,vue,ts,tsx} --fix"
},
}
5. .eslintrc.js
eslint验证规则修改为vue3
- node_modules\eslint-plugin-vue\lib\configs\vue3-strongly-recommended.js
- 参考官网
extends: [
'plugin:vue/essential',
]
# 修改为
extends: [
'plugin:vue/vue3-strongly-recommended',
]
eslint 配置 git commit hook
#git初始化
git init
#安装插件
npx mrm@2 lint-staged
package.json
修改lint-staged
"lint-staged": {
"*.{js,jsx,vue,ts,tsx}": "npm run lint"
}
#or
"lint-staged": {
"*.{js,jsx,vue,ts,tsx}": "yarn lint"
}
#删除项目文件夹中的 6
在开发和构建中进行代码规范校验
#install
npm install vite-plugin-eslint --save-dev
# or
yarn add vite-plugin-eslint --dev
- 修改
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),
eslintPlugin({
// 配置选项
cache: false // 禁用eslint缓存
})]
})
git commit规范
# For Windows:
npm install --save-dev @commitlint/config-conventional @commitlint/cli
# Configure commitlint to use conventional config
#创建commitlint.config.js
#文件内容(下面一行)
module.exports = {extends: ['@commitlint/config-conventional']}
husky
配置
# 因为前面 lint-staged 使用的npx命令 并且已经安装了husky 所以这里也需要使用 npx
# Install Husky v6
npm install husky --save-dev
# Activate hooks
npx husky install
# Add hook
npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"
vue3中setup语法糖 eslint校验出现问题
- script-setup中的编译宏
- Compiler macros such as defineProps and defineEmits generate no-undef warnings
.eslintrc.js
中添加
module.exports = {
env: {
'vue/setup-compiler-macros': true
}
}
配置转换JSX和TSX
npm i -D @vitejs/plugin-vue-jsx
- Provides Vue 3 JSX & TSX support with HMR.
vite.config.js
中添加
// vite.config.ts
import vueJsx from '@vitejs/plugin-vue-jsx'
export default {
plugins: [
vueJsx({
// options are passed on to @vue/babel-plugin-jsx
})
]
}
初始化VueRouter
npm install vue-router@4
初始化 Vuex
npm install vuex@next --save
#or
yarn add vuex@next --save
//Vuex 没有为 this.$store 属性提供开箱即用的类型声明。如果你要使用 TypeScript,首先需要声明自定义的模块补充(module augmentation)。
//为此,需要在项目文件夹中添加一个声明文件来声明 Vue 的自定义类型 ComponentCustomProperties
// src/vuex.d.ts
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
declare module '@vue/runtime-core' {
// 声明自己的 store state
interface State {
count: number
}
// 为 `this.$store` 提供类型声明
interface ComponentCustomProperties {
$store: Store<State>
}
}
//引入 InjectionKey 并将其传入 useStore 使用过的任何地方,很快就会成为一项重复性的工作。为了简化问题,可以定义自己的组合式函数来检索类型化的 store :
-----------------------------------------------
// store.ts (store/index.ts)
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
export interface State {
count: number
}
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
count: 0
}
})
// 定义自己的 `useStore` 组合式函数
export function useStore () {
return baseUseStore(key)
}
-----------------------------------------------
//现在,通过引入自定义的组合式函数,不用提供 injection key 和类型声明就可以直接得到类型化的 store:
-----------------------------------------------
// vue 组件
import { useStore } from './store'
export default {
setup () {
const store = useStore()
store.state.count // 类型为 number
}
}
配置vite中模块别名
npm i -D @types/node
vite.config.ts
中添加
import {join} from 'path'
export default defineConfig({
resolve: {
alias: {
'@': join(__dirname, 'src')
}
}
tsconfig.json
中加入paths
"compilerOptions": {
...
"paths": {
"@/*":[
"./src/*"
]
}
},
CSS样式管理
# .scss and .sass install
npm install -D sass
-
src下创建 style文件夹 创建
文件名 说明 variables.scss 全局Sass变量 mixin.scss 全局mixin common.scss 全局公共样式 transition.scss 全局过度动画样式 index.scss 组织统一导出 //variables.scss 全局Sass变量 $color: red
//index.scss 组织统一导出 @import "./common.scss"; @import "./mixin.scss"; @import "./transition.scss"; @import "./variables.scss";
// main.ts 中导入index.scss // 加载全局样式 import '@/style/index.scss'
// vite.config.ts 加入
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/style/variables.scss";'
}
}
}
})
基于axios封装请求模块
-
npm install axios #or yarn add axios
-
禁用api目录下的eslint驼峰命名验证
overrides: [ { files: ['src/api/**/*.ts'], rules: { camelcase: 'off' } } ] }
-
创建/src/utils/request.ts
//src/utils/request.ts import axios, { AxiosRequestConfig } from 'axios' // request 不支持泛型 // request.get 、post、 put支持响应数据泛型 const request = axios.create({ baseURL: 'https://www.fastmock.site/mock/5f5c83c74506389e42f1b7d88fad82f5/charles' }) // 请求拦截器 request.interceptors.request.use(function (config) { // 统一设置用户身份 token return config }, function (error) { // Do something with request error return Promise.reject(error) }) // 响应拦截器 request.interceptors.response.use(function (response) { // 统一处理接口响应错误 比如 toke过期无效 服务器端异常等 return response }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error) }) export default <T = any>(config: AxiosRequestConfig) => { return request(config).then(res => { return res.data.data as T }) }
-
创建接口类型模块/src/api/types/common.ts
//src/api/types/common.ts export interface ILoginInfo { logo_square: string; logo_rectangle: string; login_log: string; slide: string[]; }
-
创建/src/api/common.ts
//src/api/common.ts /*** * 公共基础接口封装 */ // { // "data": { // "slide": [ // "bb", // "bb" // ], // "logo_square": "aa", // "logo_rectangle": "bb", // "login_log": "cc" // }, // "msg": "ok", // "status": 200 // } import request from '@/utils/request' import type { ILoginInfo } from './types/common' export const getLoginInfo = () => { return request<ILoginInfo>({ method: 'GET', url: '/login/info' }) }
环境变量和模式
-
项目根目录创建以下文件
.env # 所有情况下都会加载的环境变量 .env.local # 所有情况下都会加载的环境变量,但会被 git 忽略 .env.development # 开发模式下加载的环境变量 .env.production # 生产模式下加载的环境变量
-
.env.development
中创建一个环境变量# 开发模式下加载的环境变量 VITE_API_BASEURL = https://www.fastmock.site/mock/5f5c83c74506389e42f1b7d88fad82f5/charles
-
src 目录下创建一个 env.d.ts 声明环境变量的类型
// eslint-disable-next-line no-unused-vars interface ImportMetaEnv { readonly VITE_API_BASEURL: string // 更多环境变量... }
-
修改/src/utils/request.ts 引用环境变量
const request = axios.create({ baseURL: import.meta.env.VITE_API_BASEURL })
跨域问题 CORS
-
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)
解决方案:
开发环境 | 生产环境 |
---|---|
在服务端配置CORS | 在服务端配置CORS |
配置开发服务器代理,比如 vite-server.proxy | 配置生产服务器代理,比如nginx |
Element-plus
- element-plus
npm install element-plus --save # or yarn add element-plus
- 创建
/src/plugins/element-plus.ts
// src/plugins/element-plus.ts import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import { App } from 'vue' export default { install (app: App) { app.use(ElementPlus, { size: 'small', zIndex: 2000 }) } }
- 创建
main.ts
中引入import elementPlus from './plugins/element-plus' createApp(App) .use(router) .use(store, key) .use(elementPlus) .mount('#app')
- 国际化-全局配置
- 修改App.vue
<template> <el-config-provider :locale="locale"> <router-view /> </el-config-provider> </template> <script setup lang="ts"> import locale from 'element-plus/lib/locale/lang/zh-cn' </script>