"feat: 优化配置管理,支持强制刷新配置,新增路径解析方法"

This commit is contained in:
熊潇 2025-04-30 17:13:45 +08:00
parent 748aef5f79
commit cf570cd35b
2 changed files with 22 additions and 7 deletions

View File

@ -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",

View File

@ -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 = <T>(onlyInitConfig?: GetConfigOpts): Config & T => {
export const useConfig = <T>(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 = <T>(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<ConfigOpts, 'envConfigFile'>) => {
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);
};