Skip to content

Commit

Permalink
feat(load-cfg): add esm module loader
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed May 31, 2018
1 parent 88d0b56 commit 12a7610
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/load-cfg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"tslint": "tslint --project ."
},
"dependencies": {
"esm": "^3.0.41",
"deepmerge": "^2.1.1",
"find-up": "^2.1.0"
},
Expand Down
18 changes: 13 additions & 5 deletions packages/load-cfg/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ import * as fs from 'fs'
import * as path from 'path'
import findup from 'find-up'
import merge from 'deepmerge'
import esm from 'esm'

export const finds = (name: string): string[] => [
`${name}.json`,
`.${name}rc`,
`${name}rc.js`,
`${name}rc.json`,
`${name}rc.yml`,
`${name}rc.yaml`,
`${name}.config.js`,
`${name}.config.json`,
]
Expand All @@ -20,6 +19,12 @@ export const loadFile = (
noCache?: boolean
) => {
let file
const require = esm(module, {
cache: !noCache,
cjs: {
cache: !noCache,
},
})

if (noCache && filepath) {
delete require.cache[path.resolve(filepath)]
Expand All @@ -28,9 +33,12 @@ export const loadFile = (
try {
const isJS = path.extname(filepath) === '.js'

file = isJS
? require(filepath)
: JSON.parse(fs.readFileSync(filepath, 'utf-8'))
if (isJS) {
const required = require(filepath)
file = required.default || required
} else {
file = JSON.parse(fs.readFileSync(filepath, 'utf-8'))
}
} catch (err) {
file = defaultFile
}
Expand Down
1 change: 1 addition & 0 deletions packages/load-cfg/src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
declare module 'deepmerge'
declare module 'esm'
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3359,6 +3359,10 @@ eslint@^4.1.1:
table "4.0.2"
text-table "~0.2.0"

esm@^3.0.41:
version "3.0.41"
resolved "https://registry.npmjs.org/esm/-/esm-3.0.41.tgz#f7e8678510e5da89afc5709f9fc1c87f289919e9"

espree@^3.5.4:
version "3.5.4"
resolved "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz#b0f447187c8a8bed944b815a660bddf5deb5d1a7"
Expand Down

0 comments on commit 12a7610

Please sign in to comment.