Skip to content

Commit

Permalink
chore!: directly use a url to create cjs context
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jul 23, 2021
1 parent 3095807 commit e7012fb
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 6 deletions.
4 changes: 3 additions & 1 deletion README.md
Expand Up @@ -50,9 +50,11 @@ This utility creates a compatible CommonJS context that is missing in ECMAScript
```js
import { createCommonJS } from 'mlly'

const { __dirname, __filename, require } = createCommonJS(import.meta)
const { __dirname, __filename, require } = createCommonJS(import.meta.url)
```
Note: `require` and `require.resolve` implementation are lazy functions. [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) will be called on first usage.
## Resolving Modules
### `resolve`
Expand Down
2 changes: 1 addition & 1 deletion lib/index.d.ts
Expand Up @@ -5,7 +5,7 @@ export interface CommonjsContext {
__dirname: string
}

export function createCommonJS (importMeta: ImportMeta) : CommonjsContext
export function createCommonJS (url: string) : CommonjsContext

// Resolve

Expand Down
6 changes: 3 additions & 3 deletions lib/index.mjs
Expand Up @@ -6,13 +6,13 @@ import { moduleResolve } from 'import-meta-resolve'

// CommonJS

export function createCommonJS (importMeta) {
const __filename = fileURLToPath(importMeta.url)
export function createCommonJS (url) {
const __filename = fileURLToPath(url)
const __dirname = dirname(__filename)

// Lazy require
let _nativeRequire
const getNativeRequire = () => _nativeRequire || (_nativeRequire = createRequire(importMeta.url))
const getNativeRequire = () => _nativeRequire || (_nativeRequire = createRequire(url))
function require (id) { return getNativeRequire()(id) }
require.resolve = (id, options) => getNativeRequire().resolve(id, options)

Expand Down
2 changes: 1 addition & 1 deletion test/cjs.mjs
@@ -1,6 +1,6 @@
import { createCommonJS } from 'mlly'

const cjs = createCommonJS(import.meta)
const cjs = createCommonJS(import.meta.url)

console.log(cjs)
console.log(cjs.require.resolve('../package.json'))

0 comments on commit e7012fb

Please sign in to comment.