Skip to content

Commit

Permalink
feat(load-cfg): set cache to require file
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed May 23, 2018
1 parent 71df2d1 commit c49fc64
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 deletions packages/load-cfg/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as fs from 'fs'
import * as path from 'path'
import * as findup from 'find-up'
import findup from 'find-up'
import merge from 'deepmerge'

const finds = (name: string): string[] => [
export const finds = (name: string): string[] => [
`${name}.json`,
`.${name}rc`,
`${name}rc.js`,
Expand All @@ -14,20 +14,40 @@ const finds = (name: string): string[] => [
`${name}.config.json`,
]

export const load = (name: string, defaultConfig: any = {}) => {
export const loadFile = (
filepath: string,
defaultFile: any = {},
noCache?: boolean
) => {
let file

if (noCache && filepath) {
delete require.cache[path.resolve(filepath)]
}

try {
const isJS = path.extname(filepath) === '.js'

file = isJS
? require(filepath)
: JSON.parse(fs.readFileSync(filepath, 'utf-8'))
} catch (err) {
file = defaultFile
}

return file
}

export const load = (
name: string,
defaultConfig: any = {},
noCache?: boolean
) => {
let file = {}
const filepath = findup.sync(finds(name))

if (filepath) {
try {
const isJS = path.extname(filepath) === '.js'

file = isJS
? require(filepath)
: JSON.parse(fs.readFileSync(filepath, 'utf-8'))
} catch (err) {
file = defaultConfig
}
file = loadFile(filepath, defaultConfig, noCache)
}

return defaultConfig !== null ? merge(defaultConfig, file) : file
Expand Down

0 comments on commit c49fc64

Please sign in to comment.