# 前言

::: danger 注意事项

本地依赖库需按需安装并初始化配置

:::

## Usage

```json
// packages.json
{
  "name": "@eciol/template",
  "version": "1.0.0",
  "dependencies": {
    "@eciol/ant-ui": "workspace:*",
    "@eciol/api": "workspace:*",
    "@eciol/assets": "workspace:*",
    "@eciol/business-ui": "workspace:*",
    "@eciol/design": "workspace:*",
    "@eciol/directives": "workspace:*",
    "@eciol/hooks": "workspace:*",
    "@eciol/layout": "workspace:*",
    "@eciol/locale": "workspace:*",
    "@eciol/request": "workspace:*",
    "@eciol/router": "workspace:*",
    "@eciol/share-ui": "workspace:*",
    "@eciol/shared": "workspace:*",
    "@eciol/store": "workspace:*",
    "@eciol/types": "workspace:*",
  },
  "devDependencies": {
    "@eciol/eslint-config": "workspace:*",
    "@eciol/stylelint-config": "workspace:*",
    "@eciol/ts-config": "workspace:*",
    "@eciol/types": "workspace:*",
    "@eciol/vite-config": "workspace:*",
  }
}

```

```ts
// initAppConfig.ts
/**
 * Application configuration
 * src/logics/initAppConfig.ts
 */
import { initAntdComponentSetting, useMessage } from '@eciol/ant-ui';
import { initDirectives } from '@eciol/directives';
import {
  changeTheme,
  initHooksSetting,
  updateColorWeak,
  updateDarkTheme,
  updateGrayMode,
  updateHeaderBgColor,
  updateSidebarBgColor,
} from '@eciol/hooks';
import { initLayoutSetting } from '@eciol/layout';
import { useI18n } from '@eciol/locale';
import { initRequest } from '@eciol/request';
import { initRouterSetting } from '@eciol/router';
import { initSharedComponentSetting } from '@eciol/share-ui';
import {
  deepMerge,
  getCommonStoragePrefix,
  getStorageShortName,
  SessionTimeoutProcessingEnum,
  ThemeEnum,
  useGlobSetting,
} from '@eciol/shared';
import { initStoreSetting, useLocaleStore, useAppStore, useAppStoreWithOut } from '@eciol/store';
import type { ProjectConfig } from '@eciol/types';

import { ResultEnum, RoleEnum } from '@/enums';
import { PageEnum } from '@/enums/pageEnum';
import { usePermission } from '@/hooks/web/usePermission';
import { LAYOUT } from '@/router/constant';
import { PAGE_NOT_FOUND_ROUTE } from '@/router/routes/basic';
import { componentSetting, DOC_URL, localeList, localeSetting, projectSetting } from '@/settings';
import { useMultipleTabStore, usePermissionStore, usePermissionStoreWithOut } from '@/store';
import { useUserStore, useUserStoreWithOut } from '@/store/modules/user';

const stp = projectSetting.sessionTimeoutProcessing;
// 为了解耦 `packages/*` 下面各模块，不再相互依赖
// 如果模块相互依赖严重，则需要对外提供解耦方式，由调用方去进行参数传递
// 各个模块需要提供 `bridge` 文件作为解耦方式
async function initPackages() {
  const _initRequest = async () => {
    const { apiUrl, uploadUrl, urlPrefix } = useGlobSetting();
    const { createErrorModal, createSuccessModal, createMessage } = useMessage();
    const { t } = useI18n();
    await initRequest(() => {
      return {
        apiUrl, // 默认请求地址
        urlPrefix, // 默认请求服务前缀
        uploadUrl, // 默认上传地址
        // authenticationScheme: '', // 默认authenticationScheme，不传默认为'Bearer'，不拼接authenticationScheme时请传入'''
        getTokenFunction: () => {
          // 获取token的函数，返回token
          const userStore = useUserStoreWithOut();
          return userStore.getToken;
        },
        createMessage: () => createMessage, // antd的message函数，用于提示信息
        createSuccessModal, // antd的modal函数，用于创建成功modal
        errorModalFunction: createErrorModal, // antd的modal函数，用于创建失败modal
        timeoutFunction: async () => {
          // 超时处理函数，用于自定义处理接口超时的逻辑
          const userStore = useUserStoreWithOut();
          userStore.setToken(undefined);
          userStore.logout(true);
        },
        unauthorizedFunction: (msg?: string) => {
          // 未登录处理函数
          const userStore = useUserStoreWithOut();
          userStore.setToken(undefined);
          if (stp === SessionTimeoutProcessingEnum.PAGE_COVERAGE) {
            userStore.setSessionTimeout(true);
          } else {
            userStore.logout(true);
          }
          return msg || t('sys.api.errMsg401');
        },
        handleErrorFunction: () => {
          // 错误处理函数
        },
        ResultEnum, // api响应结果枚举
      };
    });
  };

  initHooksSetting(() => {
    return {
      useAppStore, // app store
      useMultipleTabStore, // 多标签 store
      useUserStore, // 用户 store
      PageEnum, // 页面路径枚举
    };
  });

  initStoreSetting(() => {
    return {
      useAppStore, // app store
      useUserStore, // 用户 store
      localeSetting, // 多语言设置
      PageEnum, // 页面路径枚举
      projectSetting, // 项目设置
    };
  });

  initAntdComponentSetting(() => {
    return {
      componentSetting, // 组件设置
      usePermission, // 权限 store
      useAppStore, // app store
      localeList, // 多语言选项列表
    };
  });

  initSharedComponentSetting(() => {
    return {
      componentSetting, // 组件设置
      usePermission, // 权限 store
      useAppStore, // app store
    };
  });

  initLayoutSetting(() => {
    return {
      useMultipleTabStore,
      useAppStore, // app store
      useUserStore,
      usePermissionStore, // 多标签 store
      projectSetting, // 项目设置
      DOC_URL,
    };
  });

  initDirectives(() => {
    return {
      usePermission, // 权限 store
    };
  });

  initRouterSetting(() => {
    return {
      PageEnum,
      projectSetting,
      RoleEnum,
      useAppStoreWithOut,
      usePermissionStoreWithOut,
      useUserStoreWithOut,
      useMultipleTabStore,
      LAYOUT,
      PAGE_NOT_FOUND_ROUTE,
      RootRoute: {},
      isOutLogin: true,
    };
  });

  await Promise.all([_initRequest()]);
}

// Initial project configuration
export async function initAppConfigStore() {
  const userStore = useUserStoreWithOut();
  userStore.setTokenByCookie();
  await initPackages();
  const localeStore = useLocaleStore();
  const appStore = useAppStore();
  let projCfg: ProjectConfig = appStore.getProjectConfig as ProjectConfig;
  projCfg = deepMerge(projectSetting, projCfg || {});
  const darkMode = appStore.getDarkMode;
  const {
    colorWeak,
    grayMode,
    themeColor,
    headerSetting: { bgColor: headerBgColor } = {},
    menuSetting: { bgColor } = {},
  } = projCfg;
  try {
    grayMode && updateGrayMode(grayMode);
    colorWeak && updateColorWeak(colorWeak);
  } catch (error) {
    console.log(error);
  }
  appStore.setProjectConfig(projCfg);

  // init dark mode
  updateDarkTheme(darkMode);
  if (darkMode === ThemeEnum.DARK) {
    updateHeaderBgColor();
    updateSidebarBgColor();
  } else {
    headerBgColor && updateHeaderBgColor(headerBgColor);
    bgColor && updateSidebarBgColor(bgColor);
  }
  changeTheme(themeColor);
  // init store
  localeStore.initLocale();

  setTimeout(() => {
    clearObsoleteStorage();
  }, 16);
}

/**
 * As the version continues to iterate, there will be more and more cache keys stored in localStorage.
 * This method is used to delete useless keys
 */
export function clearObsoleteStorage() {
  const commonPrefix = getCommonStoragePrefix();
  const shortPrefix = getStorageShortName();

  [localStorage, sessionStorage].forEach((item: Storage) => {
    Object.keys(item).forEach((key) => {
      if (key && key.startsWith(commonPrefix) && !key.startsWith(shortPrefix)) {
        item.removeItem(key);
      }
    });
  });
}


```
