Skip to content

Commit

Permalink
feat: add interopDefault util (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Oct 5, 2021
1 parent feefb18 commit 0c49451
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Expand Up @@ -316,6 +316,18 @@ console.log(toDataURL(`
`))
```
### `interopDefault`
Return the default export of a module at the top-level, alongside any other named exports.
```js
// Assuming the shape { default: { foo: 'bar' }, baz: 'qux' }
import myModule from 'my-module'

// Returns { foo: 'bar', baz: 'qux' }
console.log(interopDefault(myModule))
```
## License
MIT
1 change: 1 addition & 0 deletions lib/index.d.ts
Expand Up @@ -69,3 +69,4 @@ export function fileURLToPath (id: URL | string) : string
export function normalizeid (id: URL | string) : string
export function loadURL (id: string) : Promise<string>
export function toDataURL(code: string) : string
export function interopDefault<T> (sourceModule: T): 'default' extends keyof T ? T['default'] : T
27 changes: 27 additions & 0 deletions lib/index.mjs
Expand Up @@ -107,6 +107,33 @@ export function createResolve (defaults) {
}
}

export function interopDefault (sourceModule) {
if (!(sourceModule && 'default' in sourceModule)) {
return sourceModule
}
const newModule = sourceModule.default
for (const key in sourceModule) {
if (key === 'default') {
try {
Object.defineProperty(newModule, key, {
enumerable: false,
configurable: false,
get () { return newModule }
})
} catch (_err) {}
} else {
try {
Object.defineProperty(newModule, key, {
enumerable: true,
configurable: true,
get () { return sourceModule[key] }
})
} catch (_err) {}
}
}
return newModule
}

// Evaluate

// TODO: Migrate to new Regexes
Expand Down
23 changes: 23 additions & 0 deletions test/interop.test.mjs
@@ -0,0 +1,23 @@
import { expect } from 'chai'
import { interopDefault } from '../lib/index.mjs'

const tests = [
[{}, {}],
[{ default: {} }, {}],
[{ default: { x: 2 } }, { x: 2 }],
[{ named: 2 }, { named: 2 }],
[{ named: 2, default: {} }, { named: 2 }],
[{ named: 1, default: { x: 2 } }, { named: 1, x: 2 }]
]

describe('interopDefault', () => {
for (const [input, result] of tests) {
it(JSON.stringify(input), () => {
const interop = interopDefault(input)
expect(interop).to.deep.equal(result)
if ('default' in input) {
expect(interop.default).to.deep.equal(result)
}
})
}
})

0 comments on commit 0c49451

Please sign in to comment.