0
# CommonJS Context
1
2
Utilities for creating CommonJS-compatible context within ECMAScript modules, providing __dirname, __filename, and require functionality that is missing in ESM environments.
3
4
## Capabilities
5
6
### Create CommonJS
7
8
Creates a CommonJS context for a given module URL, enabling `require`, `__filename` and `__dirname` support similar to Node.js.
9
10
```typescript { .api }
11
/**
12
* Creates a CommonJS context for a given module URL, enabling `require`, `__filename` and `__dirname` support similar to Node.js
13
* @param url - The URL of the module file to create a context for
14
* @returns A context object containing `__filename`, `__dirname` and a custom `require` function
15
*/
16
function createCommonJS(url: string): CommonjsContext;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { createCommonJS } from "mlly";
23
24
// Create CommonJS context for current module
25
const { __dirname, __filename, require } = createCommonJS(import.meta.url);
26
27
console.log(__filename); // "/path/to/current/module.mjs"
28
console.log(__dirname); // "/path/to/current"
29
30
// Use require to load CommonJS modules
31
const fs = require("fs");
32
const lodash = require("lodash");
33
34
// Use require.resolve
35
const modulePath = require.resolve("some-package");
36
```
37
38
### Interop Default
39
40
Return the default export of a module at the top-level, alongside any other named exports. Handles interoperability between ESM and CommonJS modules.
41
42
```typescript { .api }
43
/**
44
* Return the default export of a module at the top-level, alongside any other named exports
45
* @param sourceModule - The module object to process
46
* @param opts - Options for controlling interop behavior
47
* @returns The processed module with default export interop applied
48
*/
49
function interopDefault(
50
sourceModule: any,
51
opts?: { preferNamespace?: boolean }
52
): any;
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { interopDefault } from "mlly";
59
60
// Assuming a module with shape: { default: { foo: 'bar' }, baz: 'qux' }
61
const myModule = await import("my-module");
62
63
// Returns { foo: 'bar', baz: 'qux' }
64
const processed = interopDefault(myModule);
65
66
// With preferNamespace option
67
const namespace = interopDefault(myModule, { preferNamespace: true });
68
```
69
70
**Options:**
71
72
- `preferNamespace`: In case that `default` value exists but is not extendable (when is string for example), return input as-is (default is `false`, meaning `default`'s value is preferred even if cannot be extended)
73
74
## Types
75
76
```typescript { .api }
77
interface CommonjsContext {
78
/** The absolute path to the current module file */
79
__filename: string;
80
/** The directory name of the current module */
81
__dirname: string;
82
/** A function to require modules as in CommonJS */
83
require: NodeRequire;
84
}
85
```
86
87
## Key Features
88
89
### Lazy Require Implementation
90
91
The `require` function created by `createCommonJS` is implemented lazily - it only creates the actual Node.js `require` function when first called. This improves performance by avoiding unnecessary initialization.
92
93
### Full Require Compatibility
94
95
The generated `require` function supports all standard Node.js require features:
96
97
- **Module Loading**: `require("module-name")` loads CommonJS modules
98
- **Resolution**: `require.resolve("module-name")` resolves module paths
99
- **JSON Loading**: Automatically parses JSON files
100
- **Built-in Modules**: Supports Node.js built-in modules
101
102
### Path Resolution
103
104
The `__filename` and `__dirname` variables are correctly resolved from the provided URL:
105
106
- `__filename` contains the absolute file path of the current module
107
- `__dirname` contains the directory path containing the current module
108
- Both paths use the platform-appropriate path separators
109
110
### ESM to CommonJS Bridge
111
112
This functionality enables ESM modules to seamlessly interact with CommonJS ecosystems:
113
114
- Load CommonJS dependencies that don't support ESM
115
- Use tools and libraries that expect CommonJS context
116
- Maintain compatibility with existing CommonJS-based codebases
117
- Access file system paths in a familiar way