Skip to content

Commit

Permalink
feat(devOrProd): 支持自定义判定
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 21, 2022
1 parent 5206139 commit ebd8320
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/utils/devOrProd.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
function makeDevOrProd(getNodeEnv: () => 'dev' | 'prod') {
/**
* 开发环境和生产环境返回不同的值或调用不同的函数。
*
* @param devValue 开发环境返回的值或调用的函数
* @param prodValue 生产环境返回的值或调用的函数
*/
function devOrProd<R, T extends R = R, F extends () => R = () => R>(
devValue: T | F,
prodValue: T | F,
): R {
const nodeEnv = getNodeEnv()
return nodeEnv === 'prod'
? typeof prodValue === 'function'
? (prodValue as any)()
: prodValue
: typeof devValue === 'function'
? (devValue as any)()
: devValue
}

/**
* 构造 devOrProd。
*/
devOrProd.make = makeDevOrProd

return devOrProd
}

/**
* 开发环境和生产环境返回不同的值或调用不同的函数。
*
Expand All @@ -6,16 +35,9 @@
* @param devValue 开发环境返回的值或调用的函数
* @param prodValue 生产环境返回的值或调用的函数
*/
export function devOrProd<R, T extends R = R, F extends () => R = () => R>(
devValue: T | F,
prodValue: T | F,
): R {
export const devOrProd = makeDevOrProd(() => {
const nodeEnv = process.env.NODE_ENV
return !nodeEnv || nodeEnv === 'production' || nodeEnv === 'prod'
? typeof prodValue === 'function'
? (prodValue as any)()
: prodValue
: typeof devValue === 'function'
? (devValue as any)()
: devValue
}
? 'prod'
: 'dev'
})

0 comments on commit ebd8320

Please sign in to comment.