@rollup/plugin-commonjs 18.0.0-1 → 19.0.1

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,45 @@
1
1
  # @rollup/plugin-commonjs ChangeLog
2
2
 
3
+ ## v19.0.1
4
+
5
+ _2021-07-15_
6
+
7
+ ### Bugfixes
8
+
9
+ - fix: short-circuit to actual module entry point when using circular ref through a different entry (#888)
10
+
11
+ ## v19.0.0
12
+
13
+ _2021-05-07_
14
+
15
+ ### Breaking Changes
16
+
17
+ - feat!: Add support for circular dependencies (#658)
18
+
19
+ ## v18.1.0
20
+
21
+ _2021-05-04_
22
+
23
+ ### Bugfixes
24
+
25
+ - fix: idempotence issue (#871)
26
+
27
+ ### Features
28
+
29
+ - feat: Add `defaultIsModuleExports` option to match Node.js behavior (#838)
30
+
31
+ ## v18.0.0
32
+
33
+ _2021-03-26_
34
+
35
+ ### Breaking Changes
36
+
37
+ - feat!: Add ignore-dynamic-requires option (#819)
38
+
39
+ ### Bugfixes
40
+
41
+ - fix: `isRestorableCompiledEsm` should also trigger code transform (#816)
42
+
3
43
  ## v17.1.0
4
44
 
5
45
  _2021-01-29_
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
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
@@ -128,13 +128,15 @@ export function getAugmentedNamespace(n) {
128
128
  }
129
129
  `;
130
130
 
131
+ 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.');`;
132
+
131
133
  const HELPER_NON_DYNAMIC = `
132
- export function commonjsRequire (target) {
133
- 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.');
134
+ export function commonjsRequire (path) {
135
+ ${FAILED_REQUIRE_ERROR}
134
136
  }
135
137
  `;
136
138
 
137
- const HELPERS_DYNAMIC = `
139
+ const getDynamicHelpers = (ignoreDynamicRequires) => `
138
140
  export function createModule(modulePath) {
139
141
  return {
140
142
  path: modulePath,
@@ -149,8 +151,18 @@ export function commonjsRegister (path, loader) {
149
151
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
150
152
  }
151
153
 
154
+ export function commonjsRegisterOrShort (path, to) {
155
+ const resolvedPath = commonjsResolveImpl(path, null, true);
156
+ if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
157
+ DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
158
+ } else {
159
+ DYNAMIC_REQUIRE_SHORTS[path] = to;
160
+ }
161
+ }
162
+
152
163
  const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
153
164
  const DYNAMIC_REQUIRE_CACHE = Object.create(null);
165
+ const DYNAMIC_REQUIRE_SHORTS = Object.create(null);
154
166
  const DEFAULT_PARENT_MODULE = {
155
167
  id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
156
168
  };
@@ -255,10 +267,13 @@ export function commonjsResolveImpl (path, originalModuleDir, testCache) {
255
267
  const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
256
268
  if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
257
269
  return resolvedPath;
258
- };
270
+ }
271
+ if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
272
+ return resolvedPath;
273
+ }
259
274
  if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
260
275
  return resolvedPath;
261
- };
276
+ }
262
277
  }
263
278
  if (!shouldTryNodeModules) break;
264
279
  const nextDir = normalize(originalModuleDir + '/..');
@@ -277,10 +292,17 @@ export function commonjsResolve (path, originalModuleDir) {
277
292
  }
278
293
 
279
294
  export function commonjsRequire (path, originalModuleDir) {
280
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
295
+ let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
281
296
  if (resolvedPath !== null) {
282
297
  let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
283
298
  if (cachedModule) return cachedModule.exports;
299
+ let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
300
+ if (shortTo) {
301
+ cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
302
+ if (cachedModule)
303
+ return cachedModule.exports;
304
+ resolvedPath = commonjsResolveImpl(shortTo, null, true);
305
+ }
284
306
  const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
285
307
  if (loader) {
286
308
  DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
@@ -306,15 +328,17 @@ export function commonjsRequire (path, originalModuleDir) {
306
328
  return cachedModule.exports;
307
329
  };
308
330
  }
309
- return require(path);
331
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
310
332
  }
311
333
 
312
334
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
313
335
  commonjsRequire.resolve = commonjsResolve;
314
336
  `;
315
337
 
316
- function getHelpersModule(isDynamicRequireModulesEnabled) {
317
- return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
338
+ function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
339
+ return `${HELPERS}${
340
+ isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
341
+ }`;
318
342
  }
319
343
 
320
344
  /* eslint-disable import/prefer-default-export */
@@ -375,15 +399,13 @@ function getPackageEntryPoint(dirPath) {
375
399
  }
376
400
 
377
401
  function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
378
- let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
402
+ let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
379
403
  for (const dir of dynamicRequireModuleDirPaths) {
380
404
  const entryPoint = getPackageEntryPoint(dir);
381
405
 
382
- code += `\ncommonjsRegister(${JSON.stringify(
406
+ code += `\ncommonjsRegisterOrShort(${JSON.stringify(
383
407
  getVirtualPathForDynamicRequirePath(dir, commonDir)
384
- )}, function (module, exports) {
385
- module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
386
- });`;
408
+ )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`;
387
409
  }
388
410
  return code;
389
411
  }
@@ -438,9 +460,7 @@ function getDynamicRequirePaths(patterns) {
438
460
  return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
439
461
  }
440
462
 
441
- const commonJSMetaPromises = new Map();
442
-
443
- function getCommonJSMetaPromise(id) {
463
+ function getCommonJSMetaPromise(commonJSMetaPromises, id) {
444
464
  let commonJSMetaPromise = commonJSMetaPromises.get(id);
445
465
  if (commonJSMetaPromise) return commonJSMetaPromise.promise;
446
466
 
@@ -456,7 +476,7 @@ function getCommonJSMetaPromise(id) {
456
476
  return promise;
457
477
  }
458
478
 
459
- function setCommonJSMetaPromise(id, commonjsMeta) {
479
+ function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
460
480
  const commonJSMetaPromise = commonJSMetaPromises.get(id);
461
481
  if (commonJSMetaPromise) {
462
482
  if (commonJSMetaPromise.resolve) {
@@ -510,10 +530,11 @@ async function getStaticRequireProxy(
510
530
  id,
511
531
  requireReturnsDefault,
512
532
  esModulesWithDefaultExport,
513
- esModulesWithNamedExports
533
+ esModulesWithNamedExports,
534
+ commonJsMetaPromises
514
535
  ) {
515
536
  const name = getName(id);
516
- const commonjsMeta = await getCommonJSMetaPromise(id);
537
+ const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
517
538
  if (commonjsMeta && commonjsMeta.isCommonJS) {
518
539
  return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
519
540
  } else if (commonjsMeta === null) {
@@ -789,7 +810,8 @@ function rewriteExportsAndGetExportsBlock(
789
810
  code,
790
811
  HELPERS_NAME,
791
812
  exportMode,
792
- detectWrappedDefault
813
+ detectWrappedDefault,
814
+ defaultIsModuleExports
793
815
  ) {
794
816
  const exports = [];
795
817
  const exportDeclarations = [];
@@ -806,7 +828,13 @@ function rewriteExportsAndGetExportsBlock(
806
828
  } else {
807
829
  exports.push(`${exportsName} as __moduleExports`);
808
830
  if (wrapped) {
809
- getExportsWhenWrapping(exportDeclarations, exportsName, detectWrappedDefault, HELPERS_NAME);
831
+ getExportsWhenWrapping(
832
+ exportDeclarations,
833
+ exportsName,
834
+ detectWrappedDefault,
835
+ HELPERS_NAME,
836
+ defaultIsModuleExports
837
+ );
810
838
  } else {
811
839
  getExports(
812
840
  magicString,
@@ -819,7 +847,8 @@ function rewriteExportsAndGetExportsBlock(
819
847
  moduleName,
820
848
  exportsName,
821
849
  defineCompiledEsmExpressions,
822
- HELPERS_NAME
850
+ HELPERS_NAME,
851
+ defaultIsModuleExports
823
852
  );
824
853
  }
825
854
  }
@@ -850,12 +879,15 @@ function getExportsWhenWrapping(
850
879
  exportDeclarations,
851
880
  exportsName,
852
881
  detectWrappedDefault,
853
- HELPERS_NAME
882
+ HELPERS_NAME,
883
+ defaultIsModuleExports
854
884
  ) {
855
885
  exportDeclarations.push(
856
886
  `export default ${
857
- detectWrappedDefault
887
+ detectWrappedDefault && defaultIsModuleExports === 'auto'
858
888
  ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
889
+ : defaultIsModuleExports === false
890
+ ? `${exportsName}.default`
859
891
  : exportsName
860
892
  };`
861
893
  );
@@ -872,7 +904,8 @@ function getExports(
872
904
  moduleName,
873
905
  exportsName,
874
906
  defineCompiledEsmExpressions,
875
- HELPERS_NAME
907
+ HELPERS_NAME,
908
+ defaultIsModuleExports
876
909
  ) {
877
910
  let deconflictedDefaultExportName;
878
911
  // Collect and rewrite module.exports assignments
@@ -912,16 +945,14 @@ function getExports(
912
945
  magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
913
946
  }
914
947
 
915
- if (isRestorableCompiledEsm) {
916
- if (moduleExportsAssignments.length === 0) {
917
- exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
918
- } else {
919
- exportDeclarations.push(
920
- `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
921
- );
922
- }
923
- } else {
948
+ if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
924
949
  exportDeclarations.push(`export default ${exportsName};`);
950
+ } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
951
+ exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
952
+ } else {
953
+ exportDeclarations.push(
954
+ `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
955
+ );
925
956
  }
926
957
  }
927
958
 
@@ -1123,13 +1154,15 @@ function transformCommonjs(
1123
1154
  isEsModule,
1124
1155
  ignoreGlobal,
1125
1156
  ignoreRequire,
1157
+ ignoreDynamicRequires,
1126
1158
  getIgnoreTryCatchRequireStatementMode,
1127
1159
  sourceMap,
1128
1160
  isDynamicRequireModulesEnabled,
1129
1161
  dynamicRequireModuleSet,
1130
1162
  disableWrap,
1131
1163
  commonDir,
1132
- astCache
1164
+ astCache,
1165
+ defaultIsModuleExports
1133
1166
  ) {
1134
1167
  const ast = astCache || tryParse(parse, code, id);
1135
1168
  const magicString = new MagicString(code);
@@ -1402,12 +1435,14 @@ function transformCommonjs(
1402
1435
  )}`
1403
1436
  );
1404
1437
  }
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
- });
1438
+ if (!ignoreDynamicRequires) {
1439
+ if (isShorthandProperty(parent)) {
1440
+ magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1441
+ } else {
1442
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1443
+ storeName: true
1444
+ });
1445
+ }
1411
1446
  }
1412
1447
  usesDynamicRequire = true;
1413
1448
  return;
@@ -1518,7 +1553,8 @@ function transformCommonjs(
1518
1553
  uses.exports ||
1519
1554
  uses.require ||
1520
1555
  usesDynamicRequire ||
1521
- hasRemovedRequire
1556
+ hasRemovedRequire ||
1557
+ topLevelDefineCompiledEsmExpressions.length > 0
1522
1558
  ) &&
1523
1559
  (ignoreGlobal || !uses.global)
1524
1560
  ) {
@@ -1573,7 +1609,8 @@ function transformCommonjs(
1573
1609
  code,
1574
1610
  HELPERS_NAME,
1575
1611
  exportMode,
1576
- detectWrappedDefault
1612
+ detectWrappedDefault,
1613
+ defaultIsModuleExports
1577
1614
  );
1578
1615
 
1579
1616
  if (shouldWrap) {
@@ -1598,6 +1635,7 @@ function commonjs(options = {}) {
1598
1635
  const filter = createFilter(options.include, options.exclude);
1599
1636
  const {
1600
1637
  ignoreGlobal,
1638
+ ignoreDynamicRequires,
1601
1639
  requireReturnsDefault: requireReturnsDefaultOption,
1602
1640
  esmExternals
1603
1641
  } = options;
@@ -1612,6 +1650,8 @@ function commonjs(options = {}) {
1612
1650
  : Array.isArray(esmExternals)
1613
1651
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1614
1652
  : () => esmExternals;
1653
+ const defaultIsModuleExports =
1654
+ typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1615
1655
 
1616
1656
  const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1617
1657
  options.dynamicRequireTargets
@@ -1623,6 +1663,7 @@ function commonjs(options = {}) {
1623
1663
 
1624
1664
  const esModulesWithDefaultExport = new Set();
1625
1665
  const esModulesWithNamedExports = new Set();
1666
+ const commonJsMetaPromises = new Map();
1626
1667
 
1627
1668
  const ignoreRequire =
1628
1669
  typeof options.ignore === 'function'
@@ -1689,13 +1730,15 @@ function commonjs(options = {}) {
1689
1730
  isEsModule,
1690
1731
  ignoreGlobal || isEsModule,
1691
1732
  ignoreRequire,
1733
+ ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
1692
1734
  getIgnoreTryCatchRequireStatementMode,
1693
1735
  sourceMap,
1694
1736
  isDynamicRequireModulesEnabled,
1695
1737
  dynamicRequireModuleSet,
1696
1738
  disableWrap,
1697
1739
  commonDir,
1698
- ast
1740
+ ast,
1741
+ defaultIsModuleExports
1699
1742
  );
1700
1743
  }
1701
1744
 
@@ -1715,7 +1758,7 @@ function commonjs(options = {}) {
1715
1758
 
1716
1759
  load(id) {
1717
1760
  if (id === HELPERS_ID) {
1718
- return getHelpersModule(isDynamicRequireModulesEnabled);
1761
+ return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1719
1762
  }
1720
1763
 
1721
1764
  if (id.startsWith(HELPERS_ID)) {
@@ -1788,7 +1831,8 @@ function commonjs(options = {}) {
1788
1831
  actualId,
1789
1832
  getRequireReturnsDefault(actualId),
1790
1833
  esModulesWithDefaultExport,
1791
- esModulesWithNamedExports
1834
+ esModulesWithNamedExports,
1835
+ commonJsMetaPromises
1792
1836
  );
1793
1837
  }
1794
1838
 
@@ -1821,10 +1865,10 @@ function commonjs(options = {}) {
1821
1865
 
1822
1866
  moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1823
1867
  if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1824
- setCommonJSMetaPromise(id, commonjsMeta);
1868
+ setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1825
1869
  return;
1826
1870
  }
1827
- setCommonJSMetaPromise(id, null);
1871
+ setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1828
1872
  }
1829
1873
  };
1830
1874
  }