diff --git a/package.json b/package.json index 7244162..7fcf674 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,12 @@ { "name": "@kevisual/use-config", - "version": "1.0.2", + "version": "1.0.3", "types": "dist/config.d.ts", "scripts": { "build": "npm run clean && rollup -c", "watch": " rollup -c -w", "clean": "rimraf dist" }, - "publishConfig": { "access": "public" }, @@ -49,6 +48,10 @@ "./pkgs": { "import": "./dist/pkgs.mjs", "types": "./dist/pkgs.d.ts" + }, + "./context": { + "import": "./dist/context.mjs", + "types": "./dist/context.d.ts" } } } \ No newline at end of file diff --git a/rollup.config.mjs b/rollup.config.mjs index 8f2566e..b9ca1c7 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -49,4 +49,25 @@ export default [ }, plugins: [dts()], }, + { + input: 'src/context.ts', // TypeScript 入口文件 + output: { + file: 'dist/context.mjs', // 输出文件 + format: 'es', // 输出格式设置为 ES 模块 + }, + plugins: [ + resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块 + commonjs(), + typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件 + ], + external: [], + }, + { + input: 'src/context.ts', + output: { + file: 'dist/context.d.ts', + format: 'es', + }, + plugins: [dts()], + }, ]; diff --git a/src/config.ts b/src/config.ts index 8c6af23..4016451 100644 --- a/src/config.ts +++ b/src/config.ts @@ -106,7 +106,7 @@ export const useConfig = (initConfig?: any): Config & T => { return _config; }; -export const useContext = (key: string, value: any): any => { +export const useConfigContext = (key: string, value: any): any => { const _context = global as any; if (key && value) { _context[key] = value; @@ -117,7 +117,7 @@ export const useContext = (key: string, value: any): any => { } return _context; }; -export const deleteContext = (key: string): any => { +export const deleteConfigContext = (key: string): any => { const _context = global as any; if (key && _context[key]) { delete _context[key]; diff --git a/src/context.ts b/src/context.ts new file mode 100644 index 0000000..90c4116 --- /dev/null +++ b/src/context.ts @@ -0,0 +1,33 @@ +type GlobalContext = { + redis?: any; +}; +export const useContext = (initContext?: GlobalContext) => { + const context: GlobalContext = (global as any).context; + const _context = context || initContext; + !context && ((global as any)['context'] = _context); + return _context; +}; + +export const useContextKey = (key: string, init: () => T): T => { + const _context = useContext(); + if (key && init) { + _context[key] = init(); + return _context[key] as any; + } + if (key) { + return _context[key]; + } + return _context as any; +}; + +export const useContextKeySync = async (key: string, init: () => Promise): Promise => { + const _context = useContext({}); + if (key && init) { + _context[key] = await init(); + return _context[key] as any; + } + if (key) { + return _context[key]; + } + return _context as any; +};