Skip to content

Commit f11bc38

Browse files
authored
feat(commonjs): inject __esModule marker into ES namespaces and add Object prototype (#552)
* feat(commonjs): inject __esModule marker into ES namespaces * docs(commonjs): improve documentation and update types * feat(commonjs): Integrate into requireReturnsDefault option * refactor(commonjs): add early exit for namespace augmentation
1 parent da12cf9 commit f11bc38

File tree

20 files changed

+747
-204
lines changed

20 files changed

+747
-204
lines changed

packages/commonjs/README.md

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,21 @@ commonjs({
7676
Type: `string | string[]`<br>
7777
Default: `null`
7878

79-
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default non-CommonJS modules are ignored.
79+
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default, all files with extensions other than those in `extensions` or `".cjs"` are ignored, but you can exclude additional files. See also the `include` option.
8080

8181
### `include`
8282

8383
Type: `string | string[]`<br>
8484
Default: `null`
8585

86-
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default CommonJS modules are targeted.
86+
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default, all files with extension `".cjs"` or those in `extensions` are included, but you can narrow this list by only including specific files. These files will be analyzed and transpiled if either the analysis does not find ES module specific statements or `transformMixedEsModules` is `true`.
8787

8888
### `extensions`
8989

9090
Type: `string[]`<br>
9191
Default: `['.js']`
9292

93-
Search for extensions other than .js in the order specified.
93+
For extensionless imports, search for extensions other than .js in the order specified. Note that you need to make sure that non-JavaScript files are transpiled by another plugin first.
9494

9595
### `ignoreGlobal`
9696

@@ -104,28 +104,28 @@ If true, uses of `global` won't be dealt with by this plugin.
104104
Type: `boolean`<br>
105105
Default: `true`
106106

107-
If false, skips source map generation for CommonJS modules.
107+
If false, skips source map generation for CommonJS modules. This will improve performance.
108108

109109
### `transformMixedEsModules`
110110

111111
Type: `boolean`<br>
112112
Default: `false`
113113

114-
Instructs the plugin whether or not to enable mixed module transformations. This is useful in scenarios with mixed ES and CommonJS modules. Set to `true` if it's known that `require` calls should be transformed, or `false` if the code contains env detection and the `require` should survive a transformation.
114+
Instructs the plugin whether to enable mixed module transformations. This is useful in scenarios with modules that contain a mix of ES `import` statements and CommonJS `require` expressions. Set to `true` if `require` calls should be transformed to imports in mixed modules, or `false` if the `require` expressions should survive the transformation. The latter can be important if the code contains environment detection, or you are coding for an environment with special treatment for `require` calls such as [ElectronJS](https://www.electronjs.org/). See also the "ignore" option.
115115

116116
### `ignore`
117117

118118
Type: `string[] | ((id: string) => boolean)`<br>
119119
Default: `[]`
120120

121-
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function. Only use this option if you know what you're doing!
121+
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function.
122122

123123
### `esmExternals`
124124

125-
Type: `boolean | string[] || ((id: string) => boolean)`
125+
Type: `boolean | string[] | ((id: string) => boolean)`
126126
Default: `false`
127127

128-
Controls how imports from external dependencies are rendered. By default, all external dependencies are assumed to be CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency:
128+
Controls how to render imports from external dependencies. By default, this plugin assumes that all external dependencies are CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency:
129129

130130
```js
131131
// input
@@ -137,16 +137,16 @@ import foo from 'foo';
137137

138138
This is likely not desired for ES module dependencies: Here `require` should usually return the namespace to be compatible with how bundled modules are handled.
139139

140-
If you set `esmExternals` to `true`, all external dependencies are assumed to be ES modules and will adhere to the `requireReturnsDefault` option. If that option is not set, they will be rendered as namespace imports.
140+
If you set `esmExternals` to `true`, this plugins assumes that all external dependencies are ES modules and will adhere to the `requireReturnsDefault` option. If that option is not set, they will be rendered as namespace imports.
141141

142-
You can also supply an array of ids that are to be treated as ES modules, or a function that will be passed each external id to determine if it is an ES module.
142+
You can also supply an array of ids to be treated as ES modules, or a function that will be passed each external id to determine if it is an ES module.
143143

144144
### `requireReturnsDefault`
145145

146146
Type: `boolean | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
147147
Default: `false`
148148

149-
Controls what is returned when requiring an ES module or external dependency from a CommonJS file. By default, this plugin will render it as a namespace import, i.e.
149+
Controls what is returned when requiring an ES module from a CommonJS file. When using the `esmExternals` option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports, i.e.
150150

151151
```js
152152
// input
@@ -182,13 +182,44 @@ This is in line with how other bundlers handle this situation and is also the mo
182182

183183
For these situations, you can change Rollup's behaviour either globally or per module. To change it globally, set the `requireReturnsDefault` option to one of the following values:
184184

185-
- `false`: This is the default, requiring an ES module returns its namespace. For external dependencies when using `esmExternals: true`, no additional interop code is generated:
185+
- `false`: This is the default, requiring an ES module returns its namespace. This is the only option that will also add a marker `__esModule: true` to the namespace to support interop patterns in CommonJS modules that are transpiled ES modules.
186186

187187
```js
188188
// input
189189
const dep = require('dep');
190190
console.log(dep);
191191

192+
// output
193+
import * as dep$1 from 'dep';
194+
195+
function getAugmentedNamespace(n) {
196+
var a = Object.defineProperty({}, '__esModule', { value: true });
197+
Object.keys(n).forEach(function (k) {
198+
var d = Object.getOwnPropertyDescriptor(n, k);
199+
Object.defineProperty(
200+
a,
201+
k,
202+
d.get
203+
? d
204+
: {
205+
enumerable: true,
206+
get: function () {
207+
return n[k];
208+
},
209+
}
210+
);
211+
});
212+
return a;
213+
}
214+
215+
var dep = /*@__PURE__*/ getAugmentedNamespace(dep$1);
216+
217+
console.log(dep);
218+
```
219+
220+
- `"namespace"`: Like `false`, requiring an ES module returns its namespace, but the plugin does not add the `__esModule` marker and thus creates more efficient code. For external dependencies when using `esmExternals: true`, no additional interop code is generated.
221+
222+
```js
192223
// output
193224
import * as dep from 'dep';
194225

packages/commonjs/src/helpers.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ export function getDefaultExportFromCjs (x) {
3737
3838
export function createCommonjsModule(fn, basedir, module) {
3939
return module = {
40-
path: basedir,
41-
exports: {},
42-
require: function (path, base) {
43-
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
44-
}
40+
path: basedir,
41+
exports: {},
42+
require: function (path, base) {
43+
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
44+
}
4545
}, fn(module, module.exports), module.exports;
4646
}
4747
@@ -52,6 +52,21 @@ export function getDefaultExportFromNamespaceIfPresent (n) {
5252
export function getDefaultExportFromNamespaceIfNotNamed (n) {
5353
return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
5454
}
55+
56+
export function getAugmentedNamespace(n) {
57+
if (n.__esModule) return n;
58+
var a = Object.defineProperty({}, '__esModule', {value: true});
59+
Object.keys(n).forEach(function (k) {
60+
var d = Object.getOwnPropertyDescriptor(n, k);
61+
Object.defineProperty(a, k, d.get ? d : {
62+
enumerable: true,
63+
get: function () {
64+
return n[k];
65+
}
66+
});
67+
});
68+
return a;
69+
}
5570
`;
5671

5772
const HELPER_NON_DYNAMIC = `

packages/commonjs/src/index.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -189,11 +189,14 @@ export default function commonjs(options = {}) {
189189

190190
transform(code, id) {
191191
const extName = extname(id);
192-
if (extName !== '.cjs' && id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
193-
if (!filter(id) || !extensions.includes(extName)) {
194-
setIsCjsPromise(id, null);
195-
return null;
196-
}
192+
if (
193+
extName !== '.cjs' &&
194+
id !== DYNAMIC_PACKAGES_ID &&
195+
!id.startsWith(DYNAMIC_JSON_PREFIX) &&
196+
(!filter(id) || !extensions.includes(extName))
197+
) {
198+
setIsCjsPromise(id, null);
199+
return null;
197200
}
198201

199202
let transformed;

packages/commonjs/src/proxies.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@ export function getUnknownRequireProxy(id, requireReturnsDefault) {
1717
const name = getName(id);
1818
const exported =
1919
requireReturnsDefault === 'auto'
20-
? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name})`
20+
? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
2121
: requireReturnsDefault === 'preferred'
22-
? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name})`
23-
: `export default ${name}`;
22+
? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
23+
: !requireReturnsDefault
24+
? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
25+
: `export default ${name};`;
2426
return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
2527
}
2628

@@ -53,11 +55,15 @@ export async function getStaticRequireProxy(
5355
return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
5456
} else if (isCjs === null) {
5557
return getUnknownRequireProxy(id, requireReturnsDefault);
58+
} else if (!requireReturnsDefault) {
59+
return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
60+
id
61+
)}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
5662
} else if (
5763
requireReturnsDefault !== true &&
58-
(!requireReturnsDefault ||
64+
(requireReturnsDefault === 'namespace' ||
5965
!esModulesWithDefaultExport.has(id) ||
60-
(esModulesWithNamedExports.has(id) && requireReturnsDefault === 'auto'))
66+
(requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
6167
) {
6268
return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
6369
}

packages/commonjs/test/fixtures/function/esm-externals-true/_config.js

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
11
module.exports = {
22
description: 'always uses the default export when esmExternals is not used',
33
options: {
4-
external: [
5-
'external-cjs-exports',
6-
'external-cjs-module-exports',
7-
'external-esm-named',
8-
'external-esm-mixed',
9-
'external-esm-default'
10-
]
4+
external: ['external-esm-named', 'external-esm-mixed', 'external-esm-default']
115
},
126
pluginOptions: {
137
esmExternals: true
Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
const externalExports = require('external-cjs-exports');
2-
const externalModuleExports = require('external-cjs-module-exports');
31
const externalNamed = require('external-esm-named');
42
const externalMixed = require('external-esm-mixed');
53
const externalDefault = require('external-esm-default');
64

7-
t.deepEqual(externalExports, { foo: 'foo' }, 'external exports');
8-
t.deepEqual(externalModuleExports, 'bar', 'external module exports');
95
t.deepEqual(externalNamed, { foo: 'foo' }, 'external named');
106
t.deepEqual(externalMixed, { default: 'bar', foo: 'foo' }, 'external mixed');
117
t.deepEqual(externalDefault, { default: 'bar' }, 'external default');
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module.exports = {
2+
description:
3+
'returns the namespace when requiring an ES module and requireReturnsDefault is "namespace"',
4+
options: {
5+
external: ['external-esm-named', 'external-esm-mixed', 'external-esm-default']
6+
},
7+
pluginOptions: {
8+
requireReturnsDefault: 'namespace',
9+
esmExternals: true
10+
}
11+
};
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default 'bar';
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const externalNamed = require('external-esm-named');
2+
const externalMixed = require('external-esm-mixed');
3+
const externalDefault = require('external-esm-default');
4+
5+
const namedExports = require('./named.js');
6+
const mixedExports = require('./mixed.js');
7+
const defaultExport = require('./default.js');
8+
const noExports = require('./none.js');
9+
10+
t.deepEqual(namedExports, { foo: 'foo' }, 'named exports');
11+
t.deepEqual(mixedExports, { foo: 'foo', default: 'bar' }, 'mixed exports');
12+
t.deepEqual(defaultExport, { default: 'bar' }, 'default export');
13+
t.deepEqual(noExports, {}, 'no exports');
14+
t.deepEqual(externalNamed, { foo: 'foo' }, 'external named');
15+
t.deepEqual(externalMixed, { foo: 'foo', default: 'bar' }, 'external mixed');
16+
t.deepEqual(externalDefault, { default: 'bar' }, 'external default');
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const foo = 'foo';
2+
export default 'bar';

0 commit comments

Comments
 (0)