最后更新时间:2023年5月6日 【下载完整项目】
一、新建vite项目
此教程采用pnpm包管理,与npm、yarn包管理方式略有区别。
# 构建vite项目,涉及命名项目、选择技术栈等操作,这里选择vue+typescript。
pnpm create vite
# 完成之后,cd到项目目录中。
pnpm
二、使项目支持@根目录
**作用举例:**让@代表根目录,避免使用冗长的相对路径。
<script setup lang="ts">
// 【使用该配置前】
import {AppMenu} from '../../components/AppMenu.vue'
// 【使用该配置后】
import {AppMenu} from '@/components/AppMenu.vue'
</script>
// tsconfig.json
{
"compilerOptions": {
// ...
"baseUrl": "./",
"paths": {
"@/*": [
"./src/*"
]
}
}
}
首先在控制台执行安装命令。
pnpm install -D @types/node
// vite.config.ts
// ...
import path from "path"
export default {
// ...
resolve: {
alias: {
"@": path.resolve(__dirname, './src')
}
},
}
三、代理后端请求
// vite.config.ts
export default {
server: {
// ...
// 将 /v1/xxx 请求映射到 http://127.0.0.1:8080/v1/xxx
proxy: {
'/v1': {
target: 'http://127.0.0.1:8080',
changeOrigin: true
},
}
}
}
四、element-plus前端框架
(1) 安装element-plus
pnpm install --save element-plus
pnpm install -D unplugin-vue-components unplugin-auto-import
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
export default {
plugins: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
}
(2) 将element-plus默认语言调整为中文
// 将element组件默认语言调整为中文
// src->App.vue
<template>
<!-- 被包含的组件全都变为默认中文 -->
<el-config-provider :locale="zhCn">
<router-view></router-view>
</el-config-provider>
</template>
<script setup lang="ts">
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import {ElConfigProvider} from 'element-plus'
</script>
五、封装axios请求和接口
pnpm install axios qs @types/qs
// src -> requests -> http.ts
import axios from 'axios'
import QS from 'qs'
// get请求
export function get(url: string, params: any) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url: url,
params: params
}).then((res: any) => {
resolve(res.data)
}).catch((err: any) => {
reject(err)
})
})
}
// post请求
export function post(url: string, params: any) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
url: url,
data: QS.stringify(params),
}).then((res: any) => {
resolve(res.data)
}).catch((err: any) => {
reject(err)
})
})
}
// src -> requests -> api.ts
import {get, post} from "@/requests/http";
export const Login = (p: any) => post('/v1/login', p)
export const Users = (p: any) => get('/v1/user/list', p)
六、安装vue-router
pnpm install vue-router@4
// src -> plugins -> router.ts
import {createRouter, createWebHashHistory} from 'vue-router'
export const router = createRouter({
history: createWebHashHistory(),
routes: [
// ...路由
]
})
// src -> main.ts
import {createApp} from 'vue'
import App from './App.vue'
import {router} from "@/plugins/router";
const app = createApp(App)
app.use(router)
app.mount('#app')
七、安装pinia (替代Vuex)
pnpm install pinia
// src -> plugins -> store.ts
import {defineStore} from 'pinia'
export const useStore = defineStore('default', {
state: () => ({}),
getters: {},
actions: {}
})
// src -> main.ts
import {createApp} from 'vue'
import App from './App.vue'
import {router} from '@/plugins/router'
import {createPinia} from 'pinia'
const app = createApp(App)
app.use(router).use(createPinia())
app.mount('#app')
八、安装mock.js
pnpm install -D mockjs vite-plugin-mock cross-env
// package.json
"scripts": {
"dev": "cross-env NODE_ENV=development vite --host",
// ...
},
// vite.config.ts
import vue from "@vitejs/plugin-vue";
import { viteMockServe } from "vite-plugin-mock";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
// ...
viteMockServe({
supportTs: false
})
],
});
// 在根目录创建mock文件夹
// mock -> api.ts
export default [
{
url: "/api/getUsers",
method: "get",
response: () => {
return {
code: 0,
message: "ok",
data: ["tom", "jerry"],
};
},
},
];
九、浏览器兼容
pnpm install -D @vitejs/plugin-legacy
// vite.confg.ts
// ...
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
base: 'https://res.example.com/',
mode: 'production',
plugins: [
// ...
legacy({
targets: ['defaults', 'chrome >= 58'],
}),
]
})
十、代码混淆(更新)
pnpm install -D rollup-obfuscator
// vite.confg.ts
// ...
import { obfuscator } from "rollup-obfuscator";
export default defineConfig({
plugins: [
// ...
// 配置参数参考:https://github.com/javascript-obfuscator/javascript-obfuscator
obfuscator({
globalOptions: {
debugProtection: true,
debugProtectionInterval:2000,
transformObjectKeys: true,
unicodeEscapeSequence: true,
numbersToExpressions: true,
shuffleStringArray: true,
splitStrings: true,
stringArray: false,
stringArrayThreshold: 1,
identifierNamesGenerator: 'hexadecimal'
},
})
]
})
【下载完整项目】