Browse Source

perf: 使用`/** */`替换`//`注释,对编辑器的智能提示更友好

i18n
xiaoxian521 2 years ago
parent
commit
ee65ec9f72
  1. 8
      build/index.ts
  2. 6
      src/api/user.ts
  3. 2
      src/config/index.ts
  4. 2
      src/plugins/i18n.ts
  5. 14
      src/router/index.ts
  6. 20
      src/router/utils.ts
  7. 2
      src/store/modules/epTheme.ts
  8. 4
      src/store/modules/permission.ts
  9. 6
      src/store/modules/user.ts
  10. 7
      src/utils/auth.ts
  11. 14
      src/utils/http/index.ts
  12. 6
      vite.config.ts

8
build/index.ts

@ -1,6 +1,6 @@
// 处理环境变量
/** 处理环境变量 */
const warpperEnv = (envConf: Recordable): ViteEnv => { const warpperEnv = (envConf: Recordable): ViteEnv => {
// 此处为默认值,无需修改
/** 此处为默认值,无需修改 */
const ret: ViteEnv = { const ret: ViteEnv = {
VITE_PORT: 8848, VITE_PORT: 8848,
VITE_PUBLIC_PATH: "", VITE_PUBLIC_PATH: "",
@ -28,12 +28,12 @@ const warpperEnv = (envConf: Recordable): ViteEnv => {
return ret; return ret;
}; };
// 跨域代理重写
/** 跨域代理重写 */
const regExps = (value: string, reg: string): string => { const regExps = (value: string, reg: string): string => {
return value.replace(new RegExp(`^${reg}`, "g"), ""); return value.replace(new RegExp(`^${reg}`, "g"), "");
}; };
// 环境变量
/** 环境变量 */
const loadEnv = (): ViteEnv => { const loadEnv = (): ViteEnv => {
return import.meta.env; return import.meta.env;
}; };

6
src/api/user.ts

@ -6,17 +6,17 @@ type Result = {
info?: object; info?: object;
}; };
// 获取验证码
/** 获取验证码 */
export const getVerify = () => { export const getVerify = () => {
return http.request<Result>("get", "/captcha"); return http.request<Result>("get", "/captcha");
}; };
// 登录
/** 登录 */
export const getLogin = (data: object) => { export const getLogin = (data: object) => {
return http.request("post", "/login", { data }); return http.request("post", "/login", { data });
}; };
// 刷新token
/** 刷新token */
export const refreshToken = (data: object) => { export const refreshToken = (data: object) => {
return http.request("post", "/refreshToken", { data }); return http.request("post", "/refreshToken", { data });
}; };

2
src/config/index.ts

@ -27,7 +27,7 @@ const getConfig = (key?: string): ServerConfigs => {
return config; return config;
}; };
// 获取项目动态全局配置
/** 获取项目动态全局配置 */
export const getServerConfig = async (app: App): Promise<undefined> => { export const getServerConfig = async (app: App): Promise<undefined> => {
app.config.globalProperties.$config = getConfig(); app.config.globalProperties.$config = getConfig();
return axios({ return axios({

2
src/plugins/i18n.ts

@ -58,7 +58,7 @@ export function transformI18n(message: any = "") {
} }
} }
// 此函数只是配合i18n Ally插件来进行国际化智能提示,并无实际意义(只对提示起作用),如果不需要国际化可删除
/** 此函数只是配合i18n Ally插件来进行国际化智能提示,并无实际意义(只对提示起作用),如果不需要国际化可删除 */
export const $t = (key: string) => key; export const $t = (key: string) => key;
export const i18n: I18n = createI18n({ export const i18n: I18n = createI18n({

14
src/router/index.ts

@ -32,25 +32,25 @@ import homeRouter from "./modules/home";
import errorRouter from "./modules/error"; import errorRouter from "./modules/error";
import remainingRouter from "./modules/remaining"; import remainingRouter from "./modules/remaining";
// 原始静态路由(未做任何处理)
/** 原始静态路由(未做任何处理) */
const routes = [homeRouter, errorRouter]; const routes = [homeRouter, errorRouter];
// 导出处理后的静态路由(三级及以上的路由全部拍成二级)
/** 导出处理后的静态路由(三级及以上的路由全部拍成二级) */
export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes( export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
formatFlatteningRoutes(buildHierarchyTree(ascending(routes))) formatFlatteningRoutes(buildHierarchyTree(ascending(routes)))
); );
// 用于渲染菜单,保持原始层级
/** 用于渲染菜单,保持原始层级 */
export const constantMenus: Array<RouteComponent> = ascending(routes).concat( export const constantMenus: Array<RouteComponent> = ascending(routes).concat(
...remainingRouter ...remainingRouter
); );
// 不参与菜单的路由
/** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map(v => { export const remainingPaths = Object.keys(remainingRouter).map(v => {
return remainingRouter[v].path; return remainingRouter[v].path;
}); });
// 创建路由实例
/** 创建路由实例 */
export const router: Router = createRouter({ export const router: Router = createRouter({
history: getHistoryMode(), history: getHistoryMode(),
routes: constantRoutes.concat(...(remainingRouter as any)), routes: constantRoutes.concat(...(remainingRouter as any)),
@ -70,7 +70,7 @@ export const router: Router = createRouter({
} }
}); });
// 重置路由
/** 重置路由 */
export function resetRouter() { export function resetRouter() {
router.getRoutes().forEach(route => { router.getRoutes().forEach(route => {
const { name, meta } = route; const { name, meta } = route;
@ -84,7 +84,7 @@ export function resetRouter() {
usePermissionStoreHook().clearAllCachePage(); usePermissionStoreHook().clearAllCachePage();
} }
// 路由白名单
/** 路由白名单 */
const whiteList = ["/login"]; const whiteList = ["/login"];
router.beforeEach((to: toRouteType, _from, next) => { router.beforeEach((to: toRouteType, _from, next) => {

20
src/router/utils.ts

@ -21,7 +21,7 @@ const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
// 动态路由 // 动态路由
import { getAsyncRoutes } from "/@/api/routes"; import { getAsyncRoutes } from "/@/api/routes";
// 按照路由中meta下的rank等级升序来排序路由
/** 按照路由中meta下的rank等级升序来排序路由 */
function ascending(arr: any[]) { function ascending(arr: any[]) {
arr.forEach(v => { arr.forEach(v => {
if (v?.meta?.rank === null) v.meta.rank = undefined; if (v?.meta?.rank === null) v.meta.rank = undefined;
@ -38,7 +38,7 @@ function ascending(arr: any[]) {
); );
} }
// 过滤meta中showLink为false的路由
/** 过滤meta中showLink为false的路由 */
function filterTree(data: RouteComponent[]) { function filterTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter( const newTree = cloneDeep(data).filter(
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false (v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
@ -49,7 +49,7 @@ function filterTree(data: RouteComponent[]) {
return newTree; return newTree;
} }
// 批量删除缓存路由(keepalive)
/** 批量删除缓存路由(keepalive) */
function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) { function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
delAliveRouteList.forEach(route => { delAliveRouteList.forEach(route => {
usePermissionStoreHook().cacheOperate({ usePermissionStoreHook().cacheOperate({
@ -59,7 +59,7 @@ function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
}); });
} }
// 通过path获取父级路径
/** 通过path获取父级路径 */
function getParentPaths(path: string, routes: RouteRecordRaw[]) { function getParentPaths(path: string, routes: RouteRecordRaw[]) {
// 深度遍历查找 // 深度遍历查找
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) { function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
@ -83,7 +83,7 @@ function getParentPaths(path: string, routes: RouteRecordRaw[]) {
return dfs(routes, path, []); return dfs(routes, path, []);
} }
// 查找对应path的路由信息
/** 查找对应path的路由信息 */
function findRouteByPath(path: string, routes: RouteRecordRaw[]) { function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
let res = routes.find((item: { path: string }) => item.path == path); let res = routes.find((item: { path: string }) => item.path == path);
if (res) { if (res) {
@ -114,7 +114,7 @@ function addPathMatch() {
} }
} }
// 初始化路由
/** 初始化路由 */
function initRouter(name: string) { function initRouter(name: string) {
return new Promise(resolve => { return new Promise(resolve => {
getAsyncRoutes({ name }).then(({ info }) => { getAsyncRoutes({ name }).then(({ info }) => {
@ -195,7 +195,7 @@ function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
return newRoutesList; return newRoutesList;
} }
// 处理缓存路由(添加、删除、刷新)
/** 处理缓存路由(添加、删除、刷新) */
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) { function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
switch (mode) { switch (mode) {
case "add": case "add":
@ -222,7 +222,7 @@ function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
} }
} }
// 过滤后端传来的动态路由 重新生成规范路由
/** 过滤后端传来的动态路由 重新生成规范路由 */
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) { function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
if (!arrRoutes || !arrRoutes.length) return; if (!arrRoutes || !arrRoutes.length) return;
const modulesRoutesKeys = Object.keys(modulesRoutes); const modulesRoutesKeys = Object.keys(modulesRoutes);
@ -251,7 +251,7 @@ function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
return arrRoutes; return arrRoutes;
} }
// 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html
/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
function getHistoryMode(): RouterHistory { function getHistoryMode(): RouterHistory {
const routerHistory = loadEnv().VITE_ROUTER_HISTORY; const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1 // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
@ -275,7 +275,7 @@ function getHistoryMode(): RouterHistory {
} }
} }
// 是否有权限
/** 是否有权限 */
function hasPermissions(value: Array<string>): boolean { function hasPermissions(value: Array<string>): boolean {
if (value && value instanceof Array && value.length > 0) { if (value && value instanceof Array && value.length > 0) {
const roles = usePermissionStoreHook().buttonAuth; const roles = usePermissionStoreHook().buttonAuth;

2
src/store/modules/epTheme.ts

@ -18,7 +18,7 @@ export const useEpThemeStore = defineStore({
getEpThemeColor() { getEpThemeColor() {
return this.epThemeColor; return this.epThemeColor;
}, },
// 用于mix导航模式下hamburger-svg的fill属性
/** 用于mix导航模式下hamburger-svg的fill属性 */
fill() { fill() {
if (this.epTheme === "light") { if (this.epTheme === "light") {
return "#409eff"; return "#409eff";

4
src/store/modules/permission.ts

@ -20,7 +20,7 @@ export const usePermissionStore = defineStore({
cachePageList: [] cachePageList: []
}), }),
actions: { actions: {
// 获取异步路由菜单
/** 获取异步路由菜单 */
asyncActionRoutes(routes) { asyncActionRoutes(routes) {
if (this.wholeMenus.length > 0) return; if (this.wholeMenus.length > 0) return;
this.wholeMenus = filterTree( this.wholeMenus = filterTree(
@ -61,7 +61,7 @@ export const usePermissionStore = defineStore({
break; break;
} }
}, },
// 清空缓存页面
/** 清空缓存页面 */
clearAllCachePage() { clearAllCachePage() {
this.wholeMenus = []; this.wholeMenus = [];
this.menusTree = []; this.menusTree = [];

6
src/store/modules/user.ts

@ -32,7 +32,7 @@ export const useUserStore = defineStore({
SET_NAME(name) { SET_NAME(name) {
this.name = name; this.name = name;
}, },
// 登入
/** 登入 */
async loginByUsername(data) { async loginByUsername(data) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
getLogin(data) getLogin(data)
@ -47,7 +47,7 @@ export const useUserStore = defineStore({
}); });
}); });
}, },
// 登出 清空缓存
/** 登出 清空缓存 */
logOut() { logOut() {
this.token = ""; this.token = "";
this.name = ""; this.name = "";
@ -56,7 +56,7 @@ export const useUserStore = defineStore({
useMultiTagsStoreHook().handleTags("equal", routerArrays); useMultiTagsStoreHook().handleTags("equal", routerArrays);
router.push("/login"); router.push("/login");
}, },
// 刷新token
/** 刷新token */
async refreshToken(data) { async refreshToken(data) {
removeToken(); removeToken();
return refreshToken(data).then(data => { return refreshToken(data).then(data => {

7
src/utils/auth.ts

@ -9,14 +9,13 @@ type paramsMapType = {
accessToken: string; accessToken: string;
}; };
// 获取token
/** 获取token */
export function getToken() { export function getToken() {
// 此处与TokenKey相同,此写法解决初始化时Cookies中不存在TokenKey报错 // 此处与TokenKey相同,此写法解决初始化时Cookies中不存在TokenKey报错
return Cookies.get("authorized-token"); return Cookies.get("authorized-token");
} }
// 设置token以及过期时间(cookies、sessionStorage各一份)
// 后端需要将用户信息和token以及过期时间都返回给前端,过期时间主要用于刷新token
/** 设置token以及过期时间(cookies、sessionStorage各一份),后端需要将用户信息和token以及过期时间都返回给前端,过期时间主要用于刷新token */
export function setToken(data) { export function setToken(data) {
const { accessToken, expires, name } = data; const { accessToken, expires, name } = data;
// 提取关键信息进行存储 // 提取关键信息进行存储
@ -36,7 +35,7 @@ export function setToken(data) {
sessionStorage.setItem(TokenKey, dataString); sessionStorage.setItem(TokenKey, dataString);
} }
// 删除token
/** 删除token */
export function removeToken() { export function removeToken() {
Cookies.remove(TokenKey); Cookies.remove(TokenKey);
sessionStorage.removeItem(TokenKey); sessionStorage.removeItem(TokenKey);

14
src/utils/http/index.ts

@ -38,13 +38,13 @@ class PureHttp {
this.httpInterceptorsRequest(); this.httpInterceptorsRequest();
this.httpInterceptorsResponse(); this.httpInterceptorsResponse();
} }
// 初始化配置对象
/** 初始化配置对象 */
private static initConfig: PureHttpRequestConfig = {}; private static initConfig: PureHttpRequestConfig = {};
// 保存当前Axios实例对象
/** 保存当前Axios实例对象 */
private static axiosInstance: AxiosInstance = Axios.create(defaultConfig); private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);
// 请求拦截
/** 请求拦截 */
private httpInterceptorsRequest(): void { private httpInterceptorsRequest(): void {
PureHttp.axiosInstance.interceptors.request.use( PureHttp.axiosInstance.interceptors.request.use(
(config: PureHttpRequestConfig) => { (config: PureHttpRequestConfig) => {
@ -87,7 +87,7 @@ class PureHttp {
); );
} }
// 响应拦截
/** 响应拦截 */
private httpInterceptorsResponse(): void { private httpInterceptorsResponse(): void {
const instance = PureHttp.axiosInstance; const instance = PureHttp.axiosInstance;
instance.interceptors.response.use( instance.interceptors.response.use(
@ -117,7 +117,7 @@ class PureHttp {
); );
} }
// 通用请求工具函数
/** 通用请求工具函数 */
public request<T>( public request<T>(
method: RequestMethods, method: RequestMethods,
url: string, url: string,
@ -144,7 +144,7 @@ class PureHttp {
}); });
} }
// 单独抽离的post工具函数
/** 单独抽离的post工具函数 */
public post<T, P>( public post<T, P>(
url: string, url: string,
params?: T, params?: T,
@ -153,7 +153,7 @@ class PureHttp {
return this.request<P>("post", url, params, config); return this.request<P>("post", url, params, config);
} }
// 单独抽离的get工具函数
/** 单独抽离的get工具函数 */
public get<T, P>( public get<T, P>(
url: string, url: string,
params?: T, params?: T,

6
vite.config.ts

@ -5,15 +5,15 @@ import { warpperEnv, regExps } from "./build";
import { getPluginsList } from "./build/plugins"; import { getPluginsList } from "./build/plugins";
import { UserConfigExport, ConfigEnv, loadEnv } from "vite"; import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
// 当前执行node命令时文件夹的地址(工作目录)
/** 当前执行node命令时文件夹的地址(工作目录) */
const root: string = process.cwd(); const root: string = process.cwd();
// 路径查找
/** 路径查找 */
const pathResolve = (dir: string): string => { const pathResolve = (dir: string): string => {
return resolve(__dirname, ".", dir); return resolve(__dirname, ".", dir);
}; };
// 设置别名
/** 设置别名 */
const alias: Record<string, string> = { const alias: Record<string, string> = {
"/@": pathResolve("src"), "/@": pathResolve("src"),
"@build": pathResolve("build") "@build": pathResolve("build")

Loading…
Cancel
Save