Skip to content

Commit 621768b

Browse files
authored
feat(commonjs)!: return the namespace by default when requiring ESM (#507)
* feat(commonjs): require ESM namespace by default, allow configuration BREAKING CHANGES: By default, require expressions will return the namespace of internal and external modules * chore(commonjs): refactor and clean up code * chore(commonjs): add documentation * feat(commonjs): add esmExternals option * fix(commonjs): handle requiring mixed ES modules * chore(commonjs): adapt to updated dependencies
1 parent 4c65d01 commit 621768b

File tree

129 files changed

+1748
-293
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

129 files changed

+1748
-293
lines changed

codecov.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ coverage:
55
round: down
66
range: 70...100
77
status:
8-
project: 'no'
9-
patch: 'yes'
10-
comment: 'off'
8+
project: "no"
9+
patch: "yes"
10+
comment: "off"

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"ci:lint": "node scripts/run-changed.js ci:lint",
88
"ci:test": "node scripts/run-changed.js ci:test",
99
"lint": "pnpm run lint:docs && npm run lint:json && pnpm run lint:package && node scripts/run-changed.js lint",
10-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
10+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
1111
"lint:js": "eslint scripts util",
1212
"lint:json": "prettier --write tsconfig.*.json codecov.yml pnpm-workspace.yaml",
1313
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",

packages/alias/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2323
"ci:test": "pnpm run test -- --verbose",
2424
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
25-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
25+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2626
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
2727
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2828
"prebuild": "del-cli dist",

packages/auto-install/package.json

+2-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2020
"ci:test": "pnpm run test -- --verbose",
2121
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
22-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
22+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2323
"lint:js": "eslint --fix --cache src test --ext .js,.ts",
2424
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2525
"prebuild": "del-cli dist",
@@ -54,9 +54,7 @@
5454
},
5555
"types": "types/index.d.ts",
5656
"ava": {
57-
"babel": {
58-
"compileEnhancements": false
59-
},
57+
"babel": true,
6058
"extensions": [
6159
"ts"
6260
],

packages/auto-install/test/npm-bare.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const input = join(cwd, '../input.js');
1515
process.chdir(cwd);
1616

1717
test('npm, bare', async (t) => {
18-
t.timeout(30000);
18+
t.timeout(50000);
1919
await rollup({
2020
input,
2121
output: {

packages/auto-install/test/npm.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const pkgFile = join(cwd, 'package.json');
1717
process.chdir(cwd);
1818

1919
test('invalid manager', (t) => {
20-
t.timeout(30000);
20+
t.timeout(50000);
2121
const error = t.throws(
2222
() =>
2323
rollup({
@@ -36,7 +36,7 @@ test('invalid manager', (t) => {
3636
});
3737

3838
test('npm', async (t) => {
39-
t.timeout(30000);
39+
t.timeout(50000);
4040
await rollup({
4141
input,
4242
output: {

packages/auto-install/test/yarn-bare.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const input = join(cwd, '../input.js');
1515
process.chdir(cwd);
1616

1717
test('yarn, bare', async (t) => {
18-
t.timeout(30000);
18+
t.timeout(50000);
1919
await rollup({
2020
input,
2121
output: {

packages/auto-install/test/yarn.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const input = join(cwd, '../input.js');
1515
process.chdir(cwd);
1616

1717
test('yarn', async (t) => {
18-
t.timeout(30000);
18+
t.timeout(50000);
1919
await rollup({
2020
input,
2121
output: {

packages/babel/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2323
"ci:test": "pnpm run test -- --verbose",
2424
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
25-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
25+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2626
"lint:js": "eslint --fix --cache src test",
2727
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2828
"prebuild": "del-cli dist",

packages/beep/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2121
"ci:test": "ava --verbose",
2222
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
23-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
23+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2424
"lint:js": "eslint --fix --cache lib test types --ext .js,.ts",
2525
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2626
"test": "ava"

packages/buble/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2323
"ci:test": "pnpm run test -- --verbose",
2424
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
25-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
25+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2626
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
2727
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2828
"prebuild": "del-cli dist",

packages/commonjs/README.md

+137-15
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ export default {
3434
input: 'src/index.js',
3535
output: {
3636
dir: 'output',
37-
format: 'cjs'
37+
format: 'cjs',
3838
},
39-
plugins: [commonjs()]
39+
plugins: [commonjs()],
4040
};
4141
```
4242

@@ -46,7 +46,7 @@ Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#comma
4646

4747
### `dynamicRequireTargets`
4848

49-
Type: `String|Array[String]`<br>
49+
Type: `string | string[]`<br>
5050
Default: `[]`
5151

5252
Some modules contain dynamic `require` calls, or require modules that contain circular dependencies, which are not handled well by static imports.
@@ -66,60 +66,182 @@ commonjs({
6666
'!node_modules/logform/index.js',
6767
'!node_modules/logform/format.js',
6868
'!node_modules/logform/levels.js',
69-
'!node_modules/logform/browser.js'
70-
]
69+
'!node_modules/logform/browser.js',
70+
],
7171
});
7272
```
7373

7474
### `exclude`
7575

76-
Type: `String` | `Array[...String]`<br>
76+
Type: `string | string[]`<br>
7777
Default: `null`
7878

7979
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.
8080

8181
### `include`
8282

83-
Type: `String` | `Array[...String]`<br>
83+
Type: `string | string[]`<br>
8484
Default: `null`
8585

8686
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.
8787

8888
### `extensions`
8989

90-
Type: `Array[...String]`<br>
90+
Type: `string[]`<br>
9191
Default: `['.js']`
9292

9393
Search for extensions other than .js in the order specified.
9494

9595
### `ignoreGlobal`
9696

97-
Type: `Boolean`<br>
97+
Type: `boolean`<br>
9898
Default: `false`
9999

100100
If true, uses of `global` won't be dealt with by this plugin.
101101

102102
### `sourceMap`
103103

104-
Type: `Boolean`<br>
104+
Type: `boolean`<br>
105105
Default: `true`
106106

107107
If false, skips source map generation for CommonJS modules.
108108

109109
### `transformMixedEsModules`
110110

111-
Type: `Boolean`<br>
111+
Type: `boolean`<br>
112112
Default: `false`
113113

114114
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.
115115

116116
### `ignore`
117117

118-
Type: `Array[...String | (String) => Boolean]`<br>
118+
Type: `string[] | ((id: string) => boolean)`<br>
119119
Default: `[]`
120120

121121
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!
122122

123+
### `esmExternals`
124+
125+
Type: `boolean | string[] || ((id: string) => boolean)`
126+
Default: `false`
127+
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:
129+
130+
```js
131+
// input
132+
const foo = require('foo');
133+
134+
// output
135+
import foo from 'foo';
136+
```
137+
138+
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.
139+
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.
141+
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.
143+
144+
### `requireReturnsDefault`
145+
146+
Type: `boolean | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
147+
Default: `false`
148+
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.
150+
151+
```js
152+
// input
153+
const foo = require('foo');
154+
155+
// output
156+
import * as foo from 'foo';
157+
```
158+
159+
This is in line with how other bundlers handle this situation and is also the most likely behaviour in case Node should ever support this. However there are some situations where this may not be desired:
160+
161+
- There is code in an external dependency that cannot be changed where a `require` statement expects the default export to be returned from an ES module.
162+
- If the imported module is in the same bundle, Rollup will generate a namespace object for the imported module which can increase bundle size unnecessarily:
163+
164+
```js
165+
// input: main.js
166+
const dep = require('./dep.js');
167+
console.log(dep.default);
168+
169+
// input: dep.js
170+
export default 'foo';
171+
172+
// output
173+
var dep = 'foo';
174+
175+
var dep$1 = /*#__PURE__*/ Object.freeze({
176+
__proto__: null,
177+
default: dep,
178+
});
179+
180+
console.log(dep$1.default);
181+
```
182+
183+
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:
184+
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:
186+
187+
```js
188+
// input
189+
const dep = require('dep');
190+
console.log(dep);
191+
192+
// output
193+
import * as dep from 'dep';
194+
195+
console.log(dep);
196+
```
197+
198+
- `"auto"`: This is complementary to how [`output.exports`](https://rollupjs.org/guide/en/#outputexports): `"auto"` works in Rollup: If a module has a default export and no named exports, requiring that module returns the default export. In all other cases, the namespace is returned. For external dependencies when using `esmExternals: true`, a corresponding interop helper is added:
199+
200+
```js
201+
// output
202+
import * as dep$1 from 'dep';
203+
204+
function getDefaultExportFromNamespaceIfNotNamed(n) {
205+
return n &&
206+
Object.prototype.hasOwnProperty.call(n, 'default') &&
207+
Object.keys(n).length === 1
208+
? n['default']
209+
: n;
210+
}
211+
212+
var dep = getDefaultExportFromNamespaceIfNotNamed(dep$1);
213+
214+
console.log(dep);
215+
```
216+
217+
- `"preferred"`: If a module has a default export, requiring that module always returns the default export, no matter whether additional named exports exist. This is similar to how previous versions of this plugin worked. Again for external dependencies when using `esmExternals: true`, an interop helper is added:
218+
219+
```js
220+
// output
221+
import * as dep$1 from 'dep';
222+
223+
function getDefaultExportFromNamespaceIfPresent(n) {
224+
return n && Object.prototype.hasOwnProperty.call(n, 'default')
225+
? n['default']
226+
: n;
227+
}
228+
229+
var dep = getDefaultExportFromNamespaceIfPresent(dep$1);
230+
231+
console.log(dep);
232+
```
233+
234+
- `true`: This will always try to return the default export on require without checking if it actually exists. This can throw at build time if there is no default export. This is how external dependencies are handled when `esmExternals` is not used. The advantage over the other options is that, like `false`, this does not add an interop helper for external dependencies, keeping the code lean:
235+
236+
```js
237+
// output
238+
import dep from 'dep';
239+
240+
console.log(dep);
241+
```
242+
243+
To change this for individual modules, you can supply a function for `requireReturnsDefault` instead. This function will then be called once for each required ES module or external dependency with the corresponding id and allows you to return different values for different modules.
244+
123245
## Using with @rollup/plugin-node-resolve
124246

125247
Since most CommonJS packages you are importing are probably dependencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):
@@ -134,9 +256,9 @@ export default {
134256
output: {
135257
file: 'bundle.js',
136258
format: 'iife',
137-
name: 'MyModule'
259+
name: 'MyModule',
138260
},
139-
plugins: [resolve(), commonjs()]
261+
plugins: [resolve(), commonjs()],
140262
};
141263
```
142264

@@ -146,7 +268,7 @@ Symlinks are common in monorepos and are also created by the `npm link` command.
146268

147269
```js
148270
commonjs({
149-
include: /node_modules/
271+
include: /node_modules/,
150272
});
151273
```
152274

packages/commonjs/package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
2323
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
2424
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
25-
"lint:docs": "prettier --single-quote --arrow-parens avoid --write README.md",
25+
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
2626
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
2727
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
2828
"prebuild": "del-cli dist",
@@ -61,7 +61,6 @@
6161
"devDependencies": {
6262
"@rollup/plugin-json": "^4.1.0",
6363
"@rollup/plugin-node-resolve": "^8.4.0",
64-
"acorn": "^7.3.1",
6564
"locate-character": "^2.0.5",
6665
"require-relative": "^0.8.7",
6766
"rollup": "^2.23.0",

0 commit comments

Comments
 (0)