diff --git a/package.json b/package.json index 573970d..9e761b0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/use-config", - "version": "1.0.11", + "version": "1.0.12", "types": "dist/config.d.ts", "scripts": { "build": "npm run clean && tsup", diff --git a/src/env.ts b/src/env.ts index e8d91a4..0efd1c5 100644 --- a/src/env.ts +++ b/src/env.ts @@ -1,7 +1,6 @@ import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; - // 配置类型 export type Config = { PORT: number; @@ -120,13 +119,17 @@ export const getConfig = (opts?: GetConfigOpts): Config => { /** * 从全局获取 * @param initConfig 在全局未找到配置时,初始化配置的内容 - * + * @param force 是否强制重新获取配置 * @returns Config */ -export const useConfig = (onlyInitConfig?: GetConfigOpts): Config & T => { +export const useConfig = (onlyInitConfig?: GetConfigOpts, force?: boolean): Config & T => { const config = (global as any).config; - const _config = config || getConfig(onlyInitConfig); + let _config = config || getConfig(onlyInitConfig); !config && ((global as any)['config'] = _config); + if (force && onlyInitConfig) { + const _newConfig = getConfig(onlyInitConfig); + _config = mergeConfig(_newConfig); + } return _config; }; @@ -138,9 +141,12 @@ export const useConfig = (onlyInitConfig?: GetConfigOpts): Config & T => { * @param opts.fileName 配置文件名, default: config.json */ export const updateConfig = (configOpts: GetConfigOpts) => { - const _config = (global as any).config || {}; const newConfig = getConfig(configOpts); - Object.assign(_config, newConfig); + return mergeConfig(newConfig); +}; +export const mergeConfig = (config: { [key: string]: any }) => { + const _config = (global as any).config || {}; + Object.assign(_config, config); (global as any).config = _config; return _config; }; @@ -196,3 +202,12 @@ export const readJsonConfig = (opts?: Omit) => { return {}; } }; +/** + * 获取相对当前路径的path + * @param releactivePath + * @returns + */ +export const resolvePath = (releactivePath: string = '') => { + const __dirname = import.meta.url ? path.dirname(import.meta.url) : ''; + return path.resolve(__dirname, releactivePath); +};