一、vite环境搭建,构建vite-vue-ts
1, 初始化vite项目
二、项目配置
1,vue-router配置
(1)安装vue-router
npm install vue-router
(2)在src下新建一个router文件夹,作为vue-router的配置目录。此目录下再新建index.ts文件,编辑内容如下:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const history = createWebHistory()
const routes: Array<RouteRecordRaw> = [
{
path: "/",
redirect: "/home",
},
{
path: "/home",
name: "home",
component: () => import("../views/home/index.vue"),
},
];
const router = createRouter({
history,
routes
})
export default router
(3)新建一个views文件夹,作为项目界面开发目录。参考router中的配置可知,在views目录下新建home目录并新建index.vue,编辑文件如下:
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<div>Home{{ count }}</div>
</template>
(4)在main.ts中引入vue-router
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
createApp(App)
.use(router)
.mount('#app')
(5)在App.vue中使用vue-router
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
</script>
<template>
<router-view />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
2、store配置
pinia同样是一个Vue状态管理工具,它和vuex有很多相似的地方。本质上他是vuex团队核心成员开发的,在vuex上面提出了一些改进。与vuex相比,pinia去除了vuex中对于同步函数Mutations和异步函数Actions的区分。直接在Actions中便能够使用同步和异步方法(在vuex的开发计划中也将会除去同步和异步的区分)。其次相比于vuex,pinia对于typescript的支持性更好,友好的devTools支持,pinia只有1kb,简化了很多方法的写法。由于vuex比较完善,因此,pinia更加适合小型项目,vuex更加适合大型项目。
(1)安装pinia
npm install pinia
(2)项目中导入pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from "./router";
createApp(App)
.use(router)
.use(createPinia())
.mount('#app')
(3)配置状态管理专用文件,在根目录下创建一个store文件,并新建一个common.ts文件
import { defineStore } from 'pinia'
// defineStore 调用后返回一个函数,调用该函数获得 Store 实体
// 定义的defineStore(),并且它需要一个唯一的名称,common名称抽离出去作为第一个参数传递
export const useCommonStore = defineStore({
id: 'common', // common是该状态管理的唯一标志也可以使用defineStore(id,{});的形式
state: () => {
return {
current: 0
}
},
getters: {
doubleCurrent: (state) => state.current * 2
},
actions: {
setCurrent() {
this.current++
}
}
})
(4)组件中使用
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useCommonStore } from '../../store/common'
const count = ref(0)
const store = useCommonStore()
// 使普通数据变响应式的函数
const { current } = storeToRefs(store)
// 修改store值得五种方式,推荐使用action
const setCur = () => {
// 1、直接修改值
// store.current = 2
// 2、通过$patch修改,支持单个或多个属性修改
// store.$patch({ current: 5 })
// 3、$patch工厂函数方式
// store.$patch(state => {
// state.current = 9
// })
// 4、$state 缺点是必须修改整个对象
// store.$state = {
// current: 10
// }
// 5、action
store.setCurrent()
}
</script>
<template>
<div>Home{{ count }}</div>
<div>{{ current }}</div>
<button @click="setCur">set</button>
</template>
3、UI组件配置
(1)安装
npm install ant-design-vue
(2)全局引入
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
createApp(App)
.use(router)
.use(createPinia())
.use(Antd)
.mount('#app')
(3)使用
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import zhCN from 'ant-design-vue/es/locale/zh_CN'
const local = zhCN
</script>
<template>
<a-config-provider :local="local">
<router-view />
</a-config-provider>
</template>
4、sass配置
(1)安装sass
npm install sass
(2)加载全局样式
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/assets/style/index.scss";`,
},
},
}
})
5、引入axios
(1)安装axios
npm install axios
(2)请求封装,在utils目录下新建http.ts文件
import axios from 'axios';
import { message as Message } from 'ant-design-vue';
const instance = axios.create({
timeout: 20000,
withCredentials: true,
baseURL: import.meta.env.VITE_APP_BASE_URL,
});
// 添加请求拦截器
instance.interceptors.request.use(
function (config: any) {
// 在发送请求之前做些什么
return config;
},
function (error: any) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
function (response: any) {
// 对响应数据做点什么
const res = response.data;
if (res.code === 0) {
return res;
} else {
Message.error(res.message);
return Promise.reject(res);
}
},
function (error: any) {
// 对响应错误做点什么
Message.error(error?.response?.data?.message || '服务端异常');
return Promise.reject(error);
}
);
export default instance;
你可以在你的项目根目录中放置下列文件来指定环境变量
使用vite的时候要使用NODE_ENV,BASE_URL 和以 VITE_开头
6、vite.config.ts 配置
(1)配置路径别名
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
// 如果报错__dirname找不到,需要安装node,执行yarn add @types/node --save-dev
'@': path.resolve(__dirname, 'src'),
'comps': path.resolve(__dirname, 'src/components'),
}
}
})
path模块是node中的一个核心模块,需要安装让 TypeScript 支持 node.js 的依赖包—— @types/node(This package contains type definitions for Node.js)
npm install @types/node --save-dev
(2)启动配置
export default defineConfig({
server: {
host: '0.0.0.0',
port: 8080,
proxy: {
'/api/': {
target: 'http://10.11.41.218:6789',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
}
})
7、eslint配置
(1)安装EsLint
npm i -D eslint
(2)初始化配置EsLint
eslint --init
(3)选择模式: To check syntax, find problems, and enforce code style 严格模式
You can also run this command directly using 'npm init @eslint/config'.
Need to install the following packages:
@eslint/create-config
Ok to proceed? (y) y
? 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
(4)选择语言模块:选择javascript
? What type of modules does your project use? ...
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these
(5)选择语言框架 选择vue.js
? Which framework does your project use? ...
React
> Vue.js
None of these
(6)是否使用ts,视自己情况而定,我这里选择的Yes
? Does your project use TypeScript? » No / Yes
(7)代码在哪里运行 使用空格键全选 浏览器+node
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node
(8)选择一个风格:选择流行的即可
? How would you like to define a style for your project? ...
> Use a popular style guide
Answer questions about your style
(9)你想遵循哪一种风格指南? 选择 Standard 我一直用的这个社区指南,感觉很好。认可度也高
? 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
(10)您希望您的配置文件是什么格式? 选择js即可
? What format do you want your config file to be in? ...
> JavaScript
YAML
JSON
(11)会提示你是否需要安装相关npm包,用npm安装还是yarn安装,视自己情况而定,我这里选择的npm
Checking peerDependencies of eslint-config-standard@latest
The config that you've selected requires the following dependencies:
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^8.0.1 eslint-plugin-import@^2.25.2 eslint-plugin-
n@^15.0.0 eslint-plugin-promise@^6.0.0 @typescript-eslint/parser@latest
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · npm
Installing eslint-plugin-vue@latest, @typescript-eslint/eslint-plugin@latest, eslint-config-standard@latest, eslint@^8.0.1, eslint-plugin-import@^2.25.2
, eslint-plugin-n@^15.0.0, eslint-plugin-promise@^6.0.0, @typescript-eslint/parser@latest
added 102 packages in 16s
Successfully created .eslintrc.js file in D:\projects\vue3-admin
(12)安装完成后,在项目根目录会出现.eslintrc.js文件
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: [
'plugin:vue/essential',
'standard'
],
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module'
},
plugins: [
'vue',
'@typescript-eslint'
],
rules: {
}
}
(13)继续安装vite-plugin-eslint
npm i -D vite-plugin-eslint
(14)在package.json文件中添加: “@babel/eslint-parser”: “^7.17.0”,r然后执行npm install
// package.json 文件
"devDependencies": {
...
"@babel/eslint-parser": "^7.17.0"
}
(15)在package.json编写eslint运行命令
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"lint:ts": "eslint --cache --max-warnings 0 \"{src,mock}/**/*.{vue,ts,tsx}\" --fix"
},