Skip to content

系统配置

用于修改项目的主题、布局、cdn、proxy等默认基础设置

配置文件

一共 个配置文件、在 /config/default/** 目录下

├── config # 系统配置参数
    ├── default # 系统配置参数
        ├── defaultSettings.ts # 系统相关配置(cdn配置、proxy配置、水印配置、登录拦截配置、导入路由配置等)
        ├── network.ts # 网络相关配置
        ├── proxy.ts # 代理相关配置

defaultSettings.ts (系统相关配置)

typescript
/**
 * @description 导出默认通用配置
 */
const settingConfig: SettingConfig = {
  // 开发以及部署时的URL,hash模式时在不确定二级目录名称的情况下建议使用""代表相对路径或者"/二级目录/",history模式默认使用"/"或者"/二级目录/"
  publicPath: './',
  // 生产环境构建文件的目录名
  outputDir: 'dist',
  // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。
  assetsDir: 'static',
  // 标题 (包括初次加载雪花屏的标题 页面的标题 浏览器的标题)
  title: 'GX Pro Admin',
  // 短标题
  shortName: 'gx_pro_admin',
  // 标题分隔符
  titleSeparator: ' - ',
  // 标题是否反转 如果为false:"page - title",如果为ture:"title - page"
  titleReverse: false,
  // 是否开启水印
  waterMark: true,
  // 水印字符
  waterMarkTitle: 'GX Pro Admin',
  // 全局滚动区域选择器
  viewScrollRoot: '#gx-pro-admin>.gx-scrollbar>.gx-scrollbar-wrap',
  // 开启cdn
  useCdn: true,
  // cdn 默认地址
  cdnUrl: 'https://cdn.bootcdn.net/ajax/libs/{name}/{version}/{path}',
  // cdn 模块集合
  cdnModules: [
    {
      name: 'axios',
      globalName: 'axios',
      path: 'axios.min.js'
    },
    {
      name: 'dayjs',
      globalName: 'dayjs',
      path: 'dayjs.min.js'
    },
    {
      name: 'echarts',
      globalName: 'echarts',
      path: 'echarts.min.js'
    }
  ],
  // 开启proxy
  useProxy: true,
  // proxy target 支持字符串、对象
  proxyTarget: 'http://127.0.0.1:3000',
  // 接口前缀
  requestPrefix: '/api',
  // 开发环境端口号
  devPort: 8080,
  // pro版本copyright可随意修改
  copyright: 'gx12358 [email protected]',
  // 缓存路由的最大数量
  keepAliveMaxNum: 99,
  // 初次页面加载时间
  routerLoadTime: 200,
  // 路由模式,可选值为 browser 或 hash
  routerMode: 'hash',
  // 不经过token校验的路由
  routesWhiteList: [ '/user/login', '/user/register', '/exception/404', '/exception/403' ],
  // token名称
  tokenName: 'Authorization',
  // token在localStorage、sessionStorage、cookie存储的key的名称
  tokenTableName: 'GxAccessToken',
  // token存储位置localStorage sessionStorage cookie
  storage: 'localStorage',
  // token失效回退到登录页时是否记录本次的路由
  recordRoute: false,
  // 是否开启登录拦截
  loginInterception: true,
  // 是否开启登录RSA加密
  loginRSA: false,
  // authentication(前端导出路由)和all(后端导出路由)两种方式
  authentication: 'all'
}

export default settingConfig

network.ts (网络相关配置)

typescript
/**
 * @description 导出默认网路配置
 **/
const networkSetting: NetworkConfig = {
  // 最长请求时间
  requestTimeout: 10000,
  // 操作正常code,支持String、Array、Number多种类型
  successCode: [ 200, 0 ]
}
export default networkSetting

proxy.ts (代理相关配置)

typescript
/**
 * 在生产环境 代理是无法生效的,所以这里没有生产环境的配置
 * The agent cannot take effect in the production environment
 * so there is no configuration of the production environment
 * For details, please see
 * https://pro.ant.design/docs/deploy
 */
/**
 * 在生产环境 代理是无法生效的,所以这里没有生产环境的配置
 * The agent cannot take effect in the production environment
 * so there is no configuration of the production environment
 * For details, please see
 * https://pro.ant.design/docs/deploy
 */
import { ProxyOptions } from 'vite'
import { isObject, isString } from '@gx-design-vue/pro-utils'
import defaultSettings from './defaultSettings'

type ProxyTargetList = ProxyOptions & { rewrite: (path: string) => string };

export function createProxy(prefix) {
  const ret = {
    dev: {},
    test: {},
    pre: {}
  }

  if (isObject(defaultSettings.proxyTarget)) {
    Object.keys(defaultSettings.proxyTarget).forEach(prefix => {
      const proxy = {
        target: `${defaultSettings.proxyTarget[prefix]}`,
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace(new RegExp(`^${prefix}`), '')
      } as ProxyTargetList

      ret.dev[prefix] = proxy
      ret.test[prefix] = proxy
      ret.pre[prefix] = proxy
    })
  } else if (isString(defaultSettings.proxyTarget)) {
    const proxy = {
      target: `${defaultSettings.proxyTarget}`,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), '')
    }
    ret.dev[prefix] = proxy
    ret.test[prefix] = proxy
    ret.pre[prefix] = proxy
  }

  return ret
}

基础用法

平台将 /config/* 中的所有配置都注册到别名 @gx-config

typescript
import { defaultSettings, animate, themeConfig, themeColor, network, createProxy } from '@gx-config'

环境变量配置

项目的环境变量配置位于项目根目录下的 .env、.env.development、.env.production、.env.pro等自定义配置环境文件 具体可以参考 Vite 文档

bash
.env                # 在所有的环境中被载入
.env.local          # 在所有的环境中被载入,但会被 git 忽略
.env.[mode]         # 只在指定的模式中被载入
.env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略

温馨提醒

  • 只有以 VITE_ 开头的变量会被嵌入到客户端侧的包中,你可以项目代码中这样访问它们:
typescript
console.log(import.meta.env.VITE_PROT);
  • VITE_GLOB_* 开头的的变量,在打包的时候,会被加入_app.config.js配置文件当中.

具体配置

平台内置 env-modedevelopment production pro 三种

bash
# 项目启动执行环境 (value:development、production)
VITE_NODE_ENV= production/development

# 代码执行环境(value:development、pro、sit等)(其中development、pro是固定的,其他可自定义设置,这里设置了production设置了sit值)
VITE_USE_MODE = development/pro/sit

# 是否开启mock
VITE_USE_MOCK = true

# 是否删除console
VITE_DROP_CONSOLE = true

# Whether to enable gzip or brotli compression
# Optional: gzip | brotli | none
# If you need multiple forms, you can use `,` to separate
VITE_BUILD_COMPRESS = 'none'

# 使用压缩时是否删除源文件,默认为false
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE = false

# 是否使用pwa
VITE_USE_PWA = false

# 是否为打包后的文件提供传统浏览器兼容性支持
VITE_LEGACY = false

# request api前缀
VITE_BASE_URL=/mock-server

# oss信息(这里开发者配合项目配置)
VITE_OSS_BUCKET = oss-*
VITE_OSS_ORIGIN = oss-cn-*

添加自定义配置

  1. .env.[mode] 中加入 VITE_CUSTOME = 自定义,具体如下
sh
# 自定义配置
VITE_CUSTOME = 自定义
  1. 加入类型支持,在 interface ViteEnv 里加上 VITE_CUSTOME: string,具体如下
typescript
interface ViteEnv {
  VITE_CUSTOME: string;
}

打包后环境动态配置

说明

当执行pnpm build构建项目之后,会自动生成 _app.config.js 文件并插入 index.html

注意: 开发环境不会生成

js
// _app.config.js
// 变量名命名规则  __PRODUCTION__xxx_CONF__   xxx:为.env配置的VITE_GLOB_APP_SHORT_NAME
window.__PRODUCTION__VUE_VBEN_ADMIN__CONF__ = {};

作用

_app.config.js 用于项目在打包后,需要动态修改配置的需求,如接口地址。不用重新进行打包,可在打包后修改 /dist/_app.config.js 内的变量,刷新即可更新代码内的局部变量。

本地存储配置

用于配置本地存储内容信息,对缓存到浏览器的信息进行 crypto 加密 在 @/utils/storage.ts 内可以配置 localStoragesessionStoragecookie 缓存信息

typescript
export function setStorage({
  key,
  value,
  expired,
  originKey,
  encryption = true,
  type = 'local'
}: {
  key: string;
  value: any;
  originKey?: boolean;
  expired?: number;
  encryption?: boolean;
  type?: string;
}) {
  const result: LocalResult = originKey ? value : {
    value,
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    expired: expired || 0
  }
  const storageValue = isEncryption(encryption) ? Encrypt(JSON.stringify(result)) : JSON.stringify(result)
  if (type === 'local') localStorage.setItem(getStorageKey(key, originKey), storageValue)
  sessionStorage.setItem(getStorageKey(key, originKey), storageValue)
}

样式配置

less 前缀设置

用于修改项目内组件 PrefixCls 的统一前缀

less
@gx-prefix: gx;
@gx-prefix-pro: ~'@{gx-prefix}-pro';

基础用法

在 less/css 内

less
/* namespace已经全局注入,不需要额外在引入 */
@prefix-cls: ~'@{gx-prefix}-app-logo';
.@{prefix-cls} {
  width: 100%;
}

vue/ts

ts
import { getPrefixCls } from '@gx-design-vue/pro-utils'
const prefixCls = getPrefixCls({
  suffixCls: '自定义值',
  isPor: false // 是否开启pro:默认false
})
const prefixClsPro = getPrefixCls({
  suffixCls: '自定义值',
  isPor: true
})

// prefixCls => gx-design-*
// prefixClsPro => gx-design-pro-*

别名配置

平台一共内置了 个: @/* @gx-mock/* @gx-config @gx-vuex @gx-admin/hooks/* @gx-design/*,方便大家使用

json
{
  "@/*": ["src/*"], // 指向src/ 目录
  "@gx-mock/*": ["mock/*"], // 指向mock/ 目录
  "@gx-config": ["config/index.ts"], // 指向config/index.ts 文件
  "@gx-vuex": ["src/store/index.ts"], // 指向src/store/index.ts 文件 主要用于pinia,导出useStore 方法 (注意该方法已经放置在autoImport.ts 文件自动导入,可以在全文直接使用)
  "@gx-admin/hooks/*": ["src/hooks/*"], // 指向src/hooks/ 目录
  "@gx-design/*": ["src/components/GDesign/*"] // 指向src/components/GDesign/ 目录
}

基础用法

typescript
import Logo from '@/assets/logo.png'
import { defaultSettings } from '@gx-config'
import { usePermissions } from '@gx-admin/hooks/system' // 平台 hooks
import ProLayout from '@gx-design/Upload' // GDesign 组件

const store = useStore()