@rollup/plugin-commonjs 17.1.0 → 18.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @rollup/plugin-commonjs ChangeLog
2
2
 
3
+ ## v18.1.0
4
+
5
+ _2021-05-04_
6
+
7
+ ### Bugfixes
8
+
9
+ - fix: idempotence issue (#871)
10
+
11
+ ### Features
12
+
13
+ - feat: Add `defaultIsModuleExports` option to match Node.js behavior (#838)
14
+
15
+ ## v18.0.0
16
+
17
+ _2021-03-26_
18
+
19
+ ### Breaking Changes
20
+
21
+ - feat!: Add ignore-dynamic-requires option (#819)
22
+
23
+ ### Bugfixes
24
+
25
+ - fix: `isRestorableCompiledEsm` should also trigger code transform (#816)
26
+
3
27
  ## v17.1.0
4
28
 
5
29
  _2021-01-29_
package/README.md CHANGED
@@ -134,6 +134,25 @@ Due to the conversion of `require` to a static `import` - the call is hoisted to
134
134
  - `string[]`: Pass an array containing the IDs to left unconverted.
135
135
  - `((id: string) => boolean|'remove')`: Pass a function that control individual IDs.
136
136
 
137
+ ### `ignoreDynamicRequires`
138
+
139
+ Type: `boolean`
140
+ Default: false
141
+
142
+ Some `require` calls cannot be resolved statically to be translated to imports, e.g.
143
+
144
+ ```js
145
+ function wrappedRequire(target) {
146
+ return require(target);
147
+ }
148
+ wrappedRequire('foo');
149
+ wrappedRequire('bar');
150
+ ```
151
+
152
+ When this option is set to `false`, the generated code will either directly throw an error when such a call is encountered or, when `dynamicRequireTargets` is used, when such a call cannot be resolved with a configured dynamic require target.
153
+
154
+ Setting this option to `true` will instead leave the `require` call in the code or use it as a fallback for `dynamicRequireTargets`.
155
+
137
156
  ### `esmExternals`
138
157
 
139
158
  Type: `boolean | string[] | ((id: string) => boolean)`
@@ -155,6 +174,49 @@ If you set `esmExternals` to `true`, this plugins assumes that all external depe
155
174
 
156
175
  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.
157
176
 
177
+ ### `defaultIsModuleExports`
178
+
179
+ Type: `boolean | "auto"`<br>
180
+ Default: `"auto"`
181
+
182
+ Controls what is the default export when importing a CommonJS file from an ES module.
183
+
184
+ - `true`: The value of the default export is `module.exports`. This currently matches the behavior of Node.js when importing a CommonJS file.
185
+ ```js
186
+ // mod.cjs
187
+ exports.default = 3;
188
+ ```
189
+ ```js
190
+ import foo from './mod.cjs';
191
+ console.log(foo); // { default: 3 }
192
+ ```
193
+ - `false`: The value of the default export is `exports.default`.
194
+ ```js
195
+ // mod.cjs
196
+ exports.default = 3;
197
+ ```
198
+ ```js
199
+ import foo from './mod.cjs';
200
+ console.log(foo); // 3
201
+ ```
202
+ - `"auto"`: The value of the default export is `exports.default` if the CommonJS file has an `exports.__esModule === true` property; otherwise it's `module.exports`. This makes it possible to import
203
+ the default export of ES modules compiled to CommonJS as if they were not compiled.
204
+ ```js
205
+ // mod.cjs
206
+ exports.default = 3;
207
+ ```
208
+ ```js
209
+ // mod-compiled.cjs
210
+ exports.__esModule = true;
211
+ exports.default = 3;
212
+ ```
213
+ ```js
214
+ import foo from './mod.cjs';
215
+ import bar from './mod-compiled.cjs';
216
+ console.log(foo); // { default: 3 }
217
+ console.log(bar); // 3
218
+ ```
219
+
158
220
  ### `requireReturnsDefault`
159
221
 
160
222
  Type: `boolean | "namespace" | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
package/dist/index.es.js CHANGED
@@ -126,18 +126,20 @@ export function getAugmentedNamespace(n) {
126
126
  }
127
127
  `;
128
128
 
129
+ const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
130
+
129
131
  const HELPER_NON_DYNAMIC = `
130
132
  export function createCommonjsModule(fn) {
131
133
  var module = { exports: {} }
132
134
  return fn(module, module.exports), module.exports;
133
135
  }
134
136
 
135
- export function commonjsRequire (target) {
136
- throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
137
+ export function commonjsRequire (path) {
138
+ ${FAILED_REQUIRE_ERROR}
137
139
  }
138
140
  `;
139
141
 
140
- const HELPERS_DYNAMIC = `
142
+ const getDynamicHelpers = (ignoreDynamicRequires) => `
141
143
  export function createCommonjsModule(fn, basedir, module) {
142
144
  return module = {
143
145
  path: basedir,
@@ -309,15 +311,17 @@ export function commonjsRequire (path, originalModuleDir) {
309
311
  return cachedModule.exports;
310
312
  };
311
313
  }
312
- return require(path);
314
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
313
315
  }
314
316
 
315
317
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
316
318
  commonjsRequire.resolve = commonjsResolve;
317
319
  `;
318
320
 
319
- function getHelpersModule(isDynamicRequireModulesEnabled) {
320
- return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
321
+ function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
322
+ return `${HELPERS}${
323
+ isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
324
+ }`;
321
325
  }
322
326
 
323
327
  /* eslint-disable import/prefer-default-export */
@@ -447,9 +451,7 @@ function getDynamicRequirePaths(patterns) {
447
451
  return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
448
452
  }
449
453
 
450
- const isCjsPromises = new Map();
451
-
452
- function getIsCjsPromise(id) {
454
+ function getIsCjsPromise(isCjsPromises, id) {
453
455
  let isCjsPromise = isCjsPromises.get(id);
454
456
  if (isCjsPromise) return isCjsPromise.promise;
455
457
 
@@ -465,7 +467,7 @@ function getIsCjsPromise(id) {
465
467
  return promise;
466
468
  }
467
469
 
468
- function setIsCjsPromise(id, resolution) {
470
+ function setIsCjsPromise(isCjsPromises, id, resolution) {
469
471
  const isCjsPromise = isCjsPromises.get(id);
470
472
  if (isCjsPromise) {
471
473
  if (isCjsPromise.resolve) {
@@ -519,10 +521,11 @@ async function getStaticRequireProxy(
519
521
  id,
520
522
  requireReturnsDefault,
521
523
  esModulesWithDefaultExport,
522
- esModulesWithNamedExports
524
+ esModulesWithNamedExports,
525
+ isCjsPromises
523
526
  ) {
524
527
  const name = getName(id);
525
- const isCjs = await getIsCjsPromise(id);
528
+ const isCjs = await getIsCjsPromise(isCjsPromises, id);
526
529
  if (isCjs) {
527
530
  return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
528
531
  } else if (isCjs === null) {
@@ -796,7 +799,8 @@ function rewriteExportsAndGetExportsBlock(
796
799
  isRestorableCompiledEsm,
797
800
  code,
798
801
  uses,
799
- HELPERS_NAME
802
+ HELPERS_NAME,
803
+ defaultIsModuleExports
800
804
  ) {
801
805
  const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
802
806
  const moduleExportsPropertyAssignments = [];
@@ -851,19 +855,29 @@ function rewriteExportsAndGetExportsBlock(
851
855
 
852
856
  // Generate default export
853
857
  const defaultExport = [];
854
- if (isRestorableCompiledEsm) {
855
- defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
856
- } else if (
857
- (wrapped || deconflictedDefaultExportName) &&
858
- (defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
859
- ) {
860
- // eslint-disable-next-line no-param-reassign
861
- uses.commonjsHelpers = true;
862
- defaultExport.push(
863
- `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
864
- );
865
- } else {
858
+ if (defaultIsModuleExports === 'auto') {
859
+ if (isRestorableCompiledEsm) {
860
+ defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
861
+ } else if (
862
+ (wrapped || deconflictedDefaultExportName) &&
863
+ (defineCompiledEsmExpressions.length > 0 || code.includes('__esModule'))
864
+ ) {
865
+ // eslint-disable-next-line no-param-reassign
866
+ uses.commonjsHelpers = true;
867
+ defaultExport.push(
868
+ `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
869
+ );
870
+ } else {
871
+ defaultExport.push(`export default ${moduleName};`);
872
+ }
873
+ } else if (defaultIsModuleExports === true) {
866
874
  defaultExport.push(`export default ${moduleName};`);
875
+ } else if (defaultIsModuleExports === false) {
876
+ if (deconflictedDefaultExportName) {
877
+ defaultExport.push(`export default ${deconflictedDefaultExportName};`);
878
+ } else {
879
+ defaultExport.push(`export default ${moduleName}.default;`);
880
+ }
867
881
  }
868
882
 
869
883
  return `\n\n${defaultExport
@@ -1111,13 +1125,15 @@ function transformCommonjs(
1111
1125
  isEsModule,
1112
1126
  ignoreGlobal,
1113
1127
  ignoreRequire,
1128
+ ignoreDynamicRequires,
1114
1129
  getIgnoreTryCatchRequireStatementMode,
1115
1130
  sourceMap,
1116
1131
  isDynamicRequireModulesEnabled,
1117
1132
  dynamicRequireModuleSet,
1118
1133
  disableWrap,
1119
1134
  commonDir,
1120
- astCache
1135
+ astCache,
1136
+ defaultIsModuleExports
1121
1137
  ) {
1122
1138
  const ast = astCache || tryParse(parse, code, id);
1123
1139
  const magicString = new MagicString(code);
@@ -1385,12 +1401,14 @@ function transformCommonjs(
1385
1401
  )}`
1386
1402
  );
1387
1403
  }
1388
- if (isShorthandProperty(parent)) {
1389
- magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1390
- } else {
1391
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1392
- storeName: true
1393
- });
1404
+ if (!ignoreDynamicRequires) {
1405
+ if (isShorthandProperty(parent)) {
1406
+ magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1407
+ } else {
1408
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1409
+ storeName: true
1410
+ });
1411
+ }
1394
1412
  }
1395
1413
 
1396
1414
  uses.commonjsHelpers = true;
@@ -1502,7 +1520,8 @@ function transformCommonjs(
1502
1520
  uses.exports ||
1503
1521
  uses.require ||
1504
1522
  uses.commonjsHelpers ||
1505
- hasRemovedRequire
1523
+ hasRemovedRequire ||
1524
+ isRestorableCompiledEsm
1506
1525
  ) &&
1507
1526
  (ignoreGlobal || !uses.global)
1508
1527
  ) {
@@ -1531,7 +1550,8 @@ function transformCommonjs(
1531
1550
  isRestorableCompiledEsm,
1532
1551
  code,
1533
1552
  uses,
1534
- HELPERS_NAME
1553
+ HELPERS_NAME,
1554
+ defaultIsModuleExports
1535
1555
  );
1536
1556
 
1537
1557
  const importBlock = rewriteRequireExpressionsAndGetImportBlock(
@@ -1565,6 +1585,7 @@ function commonjs(options = {}) {
1565
1585
  const filter = createFilter(options.include, options.exclude);
1566
1586
  const {
1567
1587
  ignoreGlobal,
1588
+ ignoreDynamicRequires,
1568
1589
  requireReturnsDefault: requireReturnsDefaultOption,
1569
1590
  esmExternals
1570
1591
  } = options;
@@ -1579,6 +1600,8 @@ function commonjs(options = {}) {
1579
1600
  : Array.isArray(esmExternals)
1580
1601
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1581
1602
  : () => esmExternals;
1603
+ const defaultIsModuleExports =
1604
+ typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1582
1605
 
1583
1606
  const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1584
1607
  options.dynamicRequireTargets
@@ -1590,6 +1613,7 @@ function commonjs(options = {}) {
1590
1613
 
1591
1614
  const esModulesWithDefaultExport = new Set();
1592
1615
  const esModulesWithNamedExports = new Set();
1616
+ const isCjsPromises = new Map();
1593
1617
 
1594
1618
  const ignoreRequire =
1595
1619
  typeof options.ignore === 'function'
@@ -1618,6 +1642,7 @@ function commonjs(options = {}) {
1618
1642
 
1619
1643
  function transformAndCheckExports(code, id) {
1620
1644
  if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1645
+ // eslint-disable-next-line no-param-reassign
1621
1646
  code =
1622
1647
  getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1623
1648
  }
@@ -1646,6 +1671,7 @@ function commonjs(options = {}) {
1646
1671
  // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1647
1672
  if (isModuleRegisterProxy(id)) {
1648
1673
  disableWrap = true;
1674
+ // eslint-disable-next-line no-param-reassign
1649
1675
  id = unwrapModuleRegisterProxy(id);
1650
1676
  }
1651
1677
 
@@ -1656,13 +1682,15 @@ function commonjs(options = {}) {
1656
1682
  isEsModule,
1657
1683
  ignoreGlobal || isEsModule,
1658
1684
  ignoreRequire,
1685
+ ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
1659
1686
  getIgnoreTryCatchRequireStatementMode,
1660
1687
  sourceMap,
1661
1688
  isDynamicRequireModulesEnabled,
1662
1689
  dynamicRequireModuleSet,
1663
1690
  disableWrap,
1664
1691
  commonDir,
1665
- ast
1692
+ ast,
1693
+ defaultIsModuleExports
1666
1694
  );
1667
1695
  }
1668
1696
 
@@ -1682,7 +1710,7 @@ function commonjs(options = {}) {
1682
1710
 
1683
1711
  load(id) {
1684
1712
  if (id === HELPERS_ID) {
1685
- return getHelpersModule(isDynamicRequireModulesEnabled);
1713
+ return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1686
1714
  }
1687
1715
 
1688
1716
  if (id.startsWith(HELPERS_ID)) {
@@ -1722,7 +1750,8 @@ function commonjs(options = {}) {
1722
1750
  actualId,
1723
1751
  getRequireReturnsDefault(actualId),
1724
1752
  esModulesWithDefaultExport,
1725
- esModulesWithNamedExports
1753
+ esModulesWithNamedExports,
1754
+ isCjsPromises
1726
1755
  );
1727
1756
  }
1728
1757
 
@@ -1753,15 +1782,16 @@ function commonjs(options = {}) {
1753
1782
  }
1754
1783
  },
1755
1784
 
1785
+ // eslint-disable-next-line no-shadow
1756
1786
  moduleParsed({ id, meta: { commonjs } }) {
1757
1787
  if (commonjs) {
1758
1788
  const isCjs = commonjs.isCommonJS;
1759
1789
  if (isCjs != null) {
1760
- setIsCjsPromise(id, isCjs);
1790
+ setIsCjsPromise(isCjsPromises, id, isCjs);
1761
1791
  return;
1762
1792
  }
1763
1793
  }
1764
- setIsCjsPromise(id, null);
1794
+ setIsCjsPromise(isCjsPromises, id, null);
1765
1795
  }
1766
1796
  };
1767
1797
  }