bunchee 4.4.0 → 4.4.2

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/dist/bin/cli.js CHANGED
@@ -25,6 +25,13 @@ const availableExtensions = new Set([
25
25
  'cts',
26
26
  'mts'
27
27
  ]);
28
+ const suffixedExportConventions = new Set([
29
+ 'react-server',
30
+ 'react-native',
31
+ 'edge-light',
32
+ 'development',
33
+ 'production'
34
+ ]);
28
35
  const SRC = 'src';
29
36
  const DIST = 'dist';
30
37
  const dtsExtensionsMap = {
@@ -94,8 +101,9 @@ let createColors = (enabled = isColorSupported)=>({
94
101
  });
95
102
  picocolors.exports = createColors();
96
103
  picocolors.exports.createColors = createColors;
104
+
97
105
  var picocolorsExports = picocolors.exports;
98
- var pc = /*@__PURE__*/ getDefaultExportFromCjs(picocolorsExports);
106
+ var pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
99
107
 
100
108
  const defaultColorFn = (text)=>text;
101
109
  function color(prefixColor) {
@@ -202,6 +210,9 @@ const getFirstExportPath = (fullExportCondition)=>{
202
210
  }
203
211
  return fullExportCondition;
204
212
  };
213
+ const joinExportAndCondition = (exportPath, condition)=>{
214
+ return (exportPath === '.' ? '' : exportPath) + '.' + condition;
215
+ };
205
216
  function findExport(exportPath, exportCondition, paths, packageType, currentPath) {
206
217
  // Skip `types` field, it cannot be the entry point
207
218
  if (exportPath === 'types') return;
@@ -214,12 +225,20 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
214
225
  };
215
226
  } else {
216
227
  const exportJsBundlePath = getFirstExportPath(fullExportCondition);
217
- // exportPath is exportType, import, require, ...
218
- // merge to currentPath
219
- paths[currentPath] = {
220
- ...paths[currentPath],
221
- [exportPath]: exportJsBundlePath
222
- };
228
+ if (suffixedExportConventions.has(exportPath)) {
229
+ const specialPath = joinExportAndCondition(currentPath, exportPath);
230
+ paths[specialPath] = {
231
+ ...paths[specialPath],
232
+ ...exportCondition
233
+ };
234
+ } else {
235
+ // exportPath is exportType, import, require, ...
236
+ // merge to currentPath
237
+ paths[currentPath] = {
238
+ ...paths[currentPath],
239
+ [exportPath]: exportJsBundlePath
240
+ };
241
+ }
223
242
  }
224
243
  return;
225
244
  }
@@ -232,6 +251,25 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
232
251
  } else {
233
252
  // subpath is exportType, import, require, ...
234
253
  const exportType = subpath;
254
+ if (typeof exportCondition[subpath] === 'object') {
255
+ const defaultPath = exportCondition[subpath].default;
256
+ if (defaultPath) {
257
+ const nestedExportCondition = {
258
+ [exportType]: defaultPath
259
+ };
260
+ findExport(exportPath, nestedExportCondition, paths, packageType, currentPath);
261
+ }
262
+ // Find special export type, such as import: { development: './dev.js', production: './prod.js' }
263
+ const conditionSpecialTypes = Object.keys(exportCondition[exportType]).filter((key)=>suffixedExportConventions.has(key));
264
+ if (conditionSpecialTypes.length > 0) {
265
+ for (const conditionSpecialType of conditionSpecialTypes){
266
+ const nestedExportConditionPath = {
267
+ [exportType]: exportCondition[exportType][conditionSpecialType]
268
+ };
269
+ findExport(conditionSpecialType, nestedExportConditionPath, paths, packageType, currentPath);
270
+ }
271
+ }
272
+ }
235
273
  const defaultPath = typeof exportCondition[subpath] === 'object' ? exportCondition[subpath].default : exportCondition[subpath];
236
274
  const nestedExportCondition = {
237
275
  [exportType]: defaultPath
@@ -334,8 +372,15 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
334
372
  };
335
373
  }
336
374
  // main export '.' from main/module/typings
375
+ let mainExportCondition;
376
+ if (pkg.main) {
377
+ const mainExportType = isEsmPackage ? hasCjsExtension(pkg.main) ? 'require' : 'import' : 'require';
378
+ mainExportCondition = {
379
+ [mainExportType]: pkg.main
380
+ };
381
+ }
337
382
  const defaultMainExport = constructFullExportCondition({
338
- [isEsmPackage ? 'import' : 'require']: pkg.main,
383
+ ...mainExportCondition,
339
384
  module: pkg.module,
340
385
  types: getTypings(pkg)
341
386
  }, packageType);
@@ -401,9 +446,6 @@ function lint$1(pkg) {
401
446
  };
402
447
  // Validate ESM package
403
448
  if (isESM) {
404
- if (main && hasCjsExtension(main)) {
405
- state.badMainExtension = true;
406
- }
407
449
  if (exports) {
408
450
  if (typeof exports === 'string') {
409
451
  if (hasCjsExtension(exports)) {
@@ -438,6 +480,9 @@ function lint$1(pkg) {
438
480
  }
439
481
  }
440
482
  } else {
483
+ if (main && path__default.default.extname(main) === '.mjs') {
484
+ state.badMainExtension = true;
485
+ }
441
486
  // Validate CJS package
442
487
  if (exports) {
443
488
  if (typeof exports === 'string') {
@@ -474,7 +519,7 @@ function lint$1(pkg) {
474
519
  }
475
520
  }
476
521
  if (state.badMainExtension) {
477
- logger.warn('Cannot export `main` field with .cjs extension in ESM package, only .mjs and .js extensions are allowed');
522
+ logger.warn('Cannot export `main` field with .mjs extension in CJS package, only .js extension is allowed');
478
523
  }
479
524
  if (state.badMainExport) {
480
525
  logger.warn('Cannot export `exports` field with .cjs extension in ESM package, only .mjs and .js extensions are allowed');
@@ -508,7 +553,7 @@ function lint$1(pkg) {
508
553
  }
509
554
  }
510
555
 
511
- var version = "4.4.0";
556
+ var version = "4.4.2";
512
557
 
513
558
  function relativify(path) {
514
559
  return path.startsWith('.') ? path : `./${path}`;
@@ -709,7 +754,9 @@ async function prepare(cwd) {
709
754
  } else {
710
755
  // Update existing exports
711
756
  Object.keys(pkgExports).forEach((exportName)=>{
712
- pkgJson.exports[exportName] = pkgExports[exportName];
757
+ if (pkgJson.exports[exportName]) {
758
+ pkgJson.exports[exportName] = pkgExports[exportName];
759
+ }
713
760
  });
714
761
  }
715
762
  }
@@ -827,11 +874,11 @@ async function run(args) {
827
874
  if (args.prepare) {
828
875
  return await prepare(cwd);
829
876
  }
830
- const entry = source ? path__default.default.resolve(cwd, source) : '';
877
+ const cliEntry = source ? path__default.default.resolve(cwd, source) : '';
831
878
  // lint package
832
879
  await lint(cwd);
833
880
  try {
834
- await bunchee.bundle(entry, bundleConfig);
881
+ await bunchee.bundle(cliEntry, bundleConfig);
835
882
  } catch (err) {
836
883
  if (err.name === 'NOT_EXISTED') {
837
884
  help();
package/dist/index.d.ts CHANGED
@@ -33,6 +33,6 @@ type PackageMetadata = {
33
33
  typings?: string;
34
34
  };
35
35
 
36
- declare function bundle(entryPath: string, { cwd: _cwd, ...options }?: BundleConfig): Promise<any>;
36
+ declare function bundle(cliEntryPath: string, { cwd: _cwd, ...options }?: BundleConfig): Promise<any>;
37
37
 
38
38
  export { type BundleConfig, bundle };
package/dist/index.js CHANGED
@@ -82,8 +82,9 @@ let createColors = (enabled = isColorSupported)=>({
82
82
  });
83
83
  picocolors.exports = createColors();
84
84
  picocolors.exports.createColors = createColors;
85
+
85
86
  var picocolorsExports = picocolors.exports;
86
- var pc = /*@__PURE__*/ getDefaultExportFromCjs(picocolorsExports);
87
+ var pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
87
88
 
88
89
  const availableExtensions = new Set([
89
90
  'js',
@@ -228,11 +229,18 @@ async function getSourcePathFromExportPath(cwd, exportPath, exportType) {
228
229
  }
229
230
  // TODO: add unit test
230
231
  // Unlike path.basename, forcedly removing extension
231
- function filePathWithoutExtension(file) {
232
- return file ? file.replace(new RegExp(`${path__default.default.extname(file)}$`), '') : undefined;
232
+ function filePathWithoutExtension(filePath) {
233
+ if (!filePath) return;
234
+ const lastDotIndex = filePath.lastIndexOf('.');
235
+ const lastSlashIndex = filePath.lastIndexOf('/');
236
+ if (lastDotIndex !== -1 && lastDotIndex > lastSlashIndex) {
237
+ return filePath.slice(0, filePath.indexOf('.', lastSlashIndex + 1));
238
+ }
239
+ return filePath;
233
240
  }
234
241
  const nonNullable = (n)=>Boolean(n);
235
242
  const hasAvailableExtension = (filename)=>availableExtensions.has(path__default.default.extname(filename).slice(1));
243
+ const hasCjsExtension = (filename)=>path__default.default.extname(filename) === '.cjs';
236
244
  // TODO: add unit test
237
245
  const baseNameWithoutExtension = (filename)=>path__default.default.basename(filename, path__default.default.extname(filename));
238
246
 
@@ -365,23 +373,64 @@ function rawContent({ exclude }) {
365
373
  };
366
374
  }
367
375
 
376
+ function relativify(path) {
377
+ return path.startsWith('.') ? path : `./${path}`;
378
+ }
379
+
368
380
  // Alias entries to import path
369
381
  // e.g.
370
382
  // For a resolved file, if it's one of the entries,
371
383
  // aliases it as export path, such as <absolute file> -> <pkg>/<export path>
372
- function aliasEntries({ entries }) {
384
+ function aliasEntries({ entry, entries, entriesAlias, format, dts }) {
385
+ let currentDistPath = '';
386
+ const entryAliasWithoutSelf = {
387
+ ...entriesAlias,
388
+ [entry]: null
389
+ };
390
+ const pathToRelativeDistMap = new Map();
391
+ for (const [, exportCondition] of Object.entries(entries)){
392
+ var _Object_entries_find;
393
+ const { import: importCond, require: requireCond, default: defaultCond } = exportCondition.export;
394
+ const firstCond = (_Object_entries_find = Object.entries(exportCondition.export).find(([key, cond])=>key !== 'types' && cond != null)) == null ? void 0 : _Object_entries_find[1];
395
+ if (dts) {
396
+ const fallbackCond = defaultCond || firstCond;
397
+ // For cjs, use require() instead of import
398
+ const firstDistPath = (format === 'cjs' ? requireCond : importCond) || fallbackCond;
399
+ if (firstDistPath) {
400
+ if (entry !== exportCondition.source) {
401
+ pathToRelativeDistMap.set(exportCondition.source, firstDistPath);
402
+ } else {
403
+ currentDistPath = firstDistPath;
404
+ }
405
+ }
406
+ }
407
+ }
373
408
  return {
374
409
  name: 'alias',
375
410
  resolveId: {
376
411
  async handler (source, importer, options) {
377
412
  const resolvedId = await this.resolve(source, importer, options);
378
413
  if (resolvedId != null) {
379
- const aliasedId = entries[resolvedId.id];
380
- if (aliasedId != null) {
381
- return {
382
- id: aliasedId,
383
- external: true
384
- };
414
+ if (dts) {
415
+ // For types, generate relative path to the other type files,
416
+ // this will be compatible for the node10 ts module resolution.
417
+ const aliasedId = pathToRelativeDistMap.get(resolvedId.id);
418
+ if (aliasedId != null && aliasedId !== currentDistPath) {
419
+ const ext = path__default.default.extname(aliasedId);
420
+ const filePathBase = filePathWithoutExtension(path__default.default.relative(path__default.default.dirname(currentDistPath), aliasedId));
421
+ const relativePath = relativify(filePathBase + ext);
422
+ return {
423
+ id: relativePath,
424
+ external: true
425
+ };
426
+ }
427
+ } else {
428
+ const aliasedId = entryAliasWithoutSelf[resolvedId.id];
429
+ if (aliasedId != null) {
430
+ return {
431
+ id: aliasedId
432
+ };
433
+ }
385
434
  }
386
435
  }
387
436
  return null;
@@ -461,6 +510,9 @@ const getFirstExportPath = (fullExportCondition)=>{
461
510
  }
462
511
  return fullExportCondition;
463
512
  };
513
+ const joinExportAndCondition = (exportPath, condition)=>{
514
+ return (exportPath === '.' ? '' : exportPath) + '.' + condition;
515
+ };
464
516
  function findExport(exportPath, exportCondition, paths, packageType, currentPath) {
465
517
  // Skip `types` field, it cannot be the entry point
466
518
  if (exportPath === 'types') return;
@@ -473,12 +525,20 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
473
525
  };
474
526
  } else {
475
527
  const exportJsBundlePath = getFirstExportPath(fullExportCondition);
476
- // exportPath is exportType, import, require, ...
477
- // merge to currentPath
478
- paths[currentPath] = {
479
- ...paths[currentPath],
480
- [exportPath]: exportJsBundlePath
481
- };
528
+ if (suffixedExportConventions.has(exportPath)) {
529
+ const specialPath = joinExportAndCondition(currentPath, exportPath);
530
+ paths[specialPath] = {
531
+ ...paths[specialPath],
532
+ ...exportCondition
533
+ };
534
+ } else {
535
+ // exportPath is exportType, import, require, ...
536
+ // merge to currentPath
537
+ paths[currentPath] = {
538
+ ...paths[currentPath],
539
+ [exportPath]: exportJsBundlePath
540
+ };
541
+ }
482
542
  }
483
543
  return;
484
544
  }
@@ -491,6 +551,25 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
491
551
  } else {
492
552
  // subpath is exportType, import, require, ...
493
553
  const exportType = subpath;
554
+ if (typeof exportCondition[subpath] === 'object') {
555
+ const defaultPath = exportCondition[subpath].default;
556
+ if (defaultPath) {
557
+ const nestedExportCondition = {
558
+ [exportType]: defaultPath
559
+ };
560
+ findExport(exportPath, nestedExportCondition, paths, packageType, currentPath);
561
+ }
562
+ // Find special export type, such as import: { development: './dev.js', production: './prod.js' }
563
+ const conditionSpecialTypes = Object.keys(exportCondition[exportType]).filter((key)=>suffixedExportConventions.has(key));
564
+ if (conditionSpecialTypes.length > 0) {
565
+ for (const conditionSpecialType of conditionSpecialTypes){
566
+ const nestedExportConditionPath = {
567
+ [exportType]: exportCondition[exportType][conditionSpecialType]
568
+ };
569
+ findExport(conditionSpecialType, nestedExportConditionPath, paths, packageType, currentPath);
570
+ }
571
+ }
572
+ }
494
573
  const defaultPath = typeof exportCondition[subpath] === 'object' ? exportCondition[subpath].default : exportCondition[subpath];
495
574
  const nestedExportCondition = {
496
575
  [exportType]: defaultPath
@@ -593,8 +672,15 @@ function findExport(exportPath, exportCondition, paths, packageType, currentPath
593
672
  };
594
673
  }
595
674
  // main export '.' from main/module/typings
675
+ let mainExportCondition;
676
+ if (pkg.main) {
677
+ const mainExportType = isEsmPackage ? hasCjsExtension(pkg.main) ? 'require' : 'import' : 'require';
678
+ mainExportCondition = {
679
+ [mainExportType]: pkg.main
680
+ };
681
+ }
596
682
  const defaultMainExport = constructFullExportCondition({
597
- [isEsmPackage ? 'import' : 'require']: pkg.main,
683
+ ...mainExportCondition,
598
684
  module: pkg.module,
599
685
  types: getTypings(pkg)
600
686
  }, packageType);
@@ -646,10 +732,12 @@ function isEsmExportName(name, ext) {
646
732
  }
647
733
  function isCjsExportName(pkg, exportCondition, ext) {
648
734
  const isESModule = isESModulePackage(pkg.type);
649
- return !isESModule && [
735
+ const isCjsCondition = [
650
736
  'require',
651
737
  'main'
652
- ].includes(exportCondition) && ext !== 'mjs' || ext === 'cjs';
738
+ ].includes(exportCondition);
739
+ const isNotEsmExportName = !isEsmExportName(exportCondition, ext);
740
+ return !isESModule && isNotEsmExportName && (ext !== 'mjs' || isCjsCondition) || ext === 'cjs';
653
741
  }
654
742
  function getExportsDistFilesOfCondition(pkg, parsedExportCondition, cwd) {
655
743
  const dist = [];
@@ -700,7 +788,7 @@ const swcMinifyOptions = {
700
788
  }
701
789
  };
702
790
  // return { 'process.env.<key>': '<value>' }
703
- function getBuildEnv(envs, exportConditions) {
791
+ function getBuildEnv(envs, parsedExportCondition) {
704
792
  if (!envs.includes('NODE_ENV')) {
705
793
  envs.push('NODE_ENV');
706
794
  }
@@ -711,8 +799,10 @@ function getBuildEnv(envs, exportConditions) {
711
799
  }
712
800
  return acc;
713
801
  }, {});
802
+ // handle .development, .production
803
+ const condName = parsedExportCondition.name.startsWith('.') ? parsedExportCondition.name.slice(1) : parsedExportCondition.name;
804
+ const exportConditionNames = new Set(Object.keys(parsedExportCondition.export).concat(condName));
714
805
  // For development and production convention, we override the NODE_ENV value
715
- const exportConditionNames = new Set(Object.keys(exportConditions));
716
806
  if (exportConditionNames.has('development')) {
717
807
  envVars['process.env.NODE_ENV'] = JSON.stringify('development');
718
808
  } else if (exportConditionNames.has('production')) {
@@ -735,15 +825,16 @@ function getBuildEnv(envs, exportConditions) {
735
825
  }
736
826
  return alias;
737
827
  }
738
- async function buildInputConfig(entry, options, buildContext, exportCondition, dts) {
828
+ async function buildInputConfig(entry, bundleConfig, exportCondition, buildContext, dts) {
829
+ var _bundleConfig_file;
739
830
  const { entries, pkg, cwd, tsOptions: { tsConfigPath, tsCompilerOptions }, pluginContext } = buildContext;
740
- const hasNoExternal = options.external === null;
741
- var _options_external;
831
+ const hasNoExternal = bundleConfig.external === null;
832
+ var _bundleConfig_external;
742
833
  const externals = hasNoExternal ? [] : [
743
834
  pkg.peerDependencies,
744
835
  pkg.dependencies,
745
836
  pkg.peerDependenciesMeta
746
- ].filter((n)=>Boolean(n)).map((o)=>Object.keys(o)).reduce((a, b)=>a.concat(b), []).concat((_options_external = options.external) != null ? _options_external : []);
837
+ ].filter((n)=>Boolean(n)).map((o)=>Object.keys(o)).reduce((a, b)=>a.concat(b), []).concat((_bundleConfig_external = bundleConfig.external) != null ? _bundleConfig_external : []);
747
838
  for (const [exportImportPath, exportCondition] of Object.entries(entries)){
748
839
  const entryFilePath = exportCondition.source;
749
840
  if (entryFilePath !== entry) {
@@ -751,9 +842,9 @@ async function buildInputConfig(entry, options, buildContext, exportCondition, d
751
842
  externals.push(entryFilePath);
752
843
  }
753
844
  }
754
- const envValues = getBuildEnv(options.env || [], exportCondition.export);
845
+ const envValues = getBuildEnv(bundleConfig.env || [], exportCondition);
755
846
  const { useTypeScript } = buildContext;
756
- const { runtime, target: jscTarget, minify: shouldMinify } = options;
847
+ const { runtime, target: jscTarget, minify: shouldMinify } = bundleConfig;
757
848
  const hasSpecifiedTsTarget = Boolean(tsCompilerOptions.target && tsConfigPath);
758
849
  const swcParserConfig = {
759
850
  syntax: useTypeScript ? 'typescript' : 'ecmascript',
@@ -771,24 +862,25 @@ async function buildInputConfig(entry, options, buildContext, exportCondition, d
771
862
  ...shouldMinify && {
772
863
  minify: {
773
864
  ...swcMinifyOptions,
774
- sourceMap: options.sourcemap
865
+ sourceMap: bundleConfig.sourcemap
775
866
  }
776
867
  }
777
868
  },
778
- sourceMaps: options.sourcemap,
869
+ sourceMaps: bundleConfig.sourcemap,
779
870
  inlineSourcesContent: false,
780
871
  isModule: true
781
872
  };
782
873
  const sizePlugin = pluginContext.outputState.plugin(cwd);
783
874
  // common plugins for both dts and ts assets that need to be processed
875
+ const aliasFormat = dts ? ((_bundleConfig_file = bundleConfig.file) == null ? void 0 : _bundleConfig_file.endsWith('.d.cts')) ? 'cjs' : 'esm' : bundleConfig.format;
784
876
  const commonPlugins = [
785
877
  sizePlugin,
786
878
  aliasEntries({
787
- entries: {
788
- ...pluginContext.entriesAlias,
789
- // Do not alias current alias of package
790
- [entry]: null
791
- }
879
+ entry,
880
+ entries,
881
+ entriesAlias: pluginContext.entriesAlias,
882
+ format: aliasFormat,
883
+ dts
792
884
  })
793
885
  ];
794
886
  const typesPlugins = [
@@ -798,6 +890,13 @@ async function buildInputConfig(entry, options, buildContext, exportCondition, d
798
890
  })
799
891
  ];
800
892
  if (useTypeScript) {
893
+ const enableIncrementalWithoutBuildInfo = tsCompilerOptions.incremental && !tsCompilerOptions.tsBuildInfoFile;
894
+ const incrementalOptions = enableIncrementalWithoutBuildInfo ? {
895
+ incremental: false
896
+ } : undefined;
897
+ const compositeOptions = tsCompilerOptions.composite && enableIncrementalWithoutBuildInfo ? {
898
+ composite: false
899
+ } : undefined;
801
900
  const { options: overrideResolvedTsOptions } = await convertCompilerOptions(cwd, {
802
901
  declaration: true,
803
902
  noEmit: false,
@@ -812,9 +911,9 @@ async function buildInputConfig(entry, options, buildContext, exportCondition, d
812
911
  } : undefined,
813
912
  // error TS5074: Option '--incremental' can only be specified using tsconfig, emitting to single
814
913
  // file or when option '--tsBuildInfoFile' is specified.
815
- ...tsCompilerOptions.incremental && !tsCompilerOptions.tsBuildInfoFile ? {
816
- incremental: false
817
- } : undefined
914
+ ...incrementalOptions,
915
+ // error TS6379: Composite projects may not disable incremental compilation.
916
+ ...compositeOptions
818
917
  });
819
918
  const dtsPlugin = require('rollup-plugin-dts').default({
820
919
  tsconfig: tsConfigPath,
@@ -841,17 +940,18 @@ async function buildInputConfig(entry, options, buildContext, exportCondition, d
841
940
  preferBuiltins: runtime === 'node',
842
941
  extensions: nodeResolveExtensions
843
942
  }),
844
- commonjs__default.default({
845
- exclude: options.external || null
846
- }),
847
- json__default.default(),
848
943
  pluginWasm.wasm(),
849
944
  rollupPluginSwc3.swc({
850
945
  include: availableESExtensionsRegex,
851
946
  exclude: 'node_modules',
852
- tsconfig: tsConfigPath,
947
+ // Use `false` to disable retrieving tsconfig.json
948
+ tsconfig: tsConfigPath != null ? tsConfigPath : false,
853
949
  ...swcOptions
854
- })
950
+ }),
951
+ commonjs__default.default({
952
+ exclude: bundleConfig.external || null
953
+ }),
954
+ json__default.default()
855
955
  ]).filter(isNotNull);
856
956
  return {
857
957
  input: entry,
@@ -959,20 +1059,21 @@ function createSplitChunks(dependencyGraphMap, entryFiles) {
959
1059
  return;
960
1060
  };
961
1061
  }
962
- function buildOutputConfigs(options, exportCondition, buildContext, dts) {
963
- const { format } = options;
1062
+ async function buildOutputConfigs(entry, bundleConfig, exportCondition, buildContext, dts) {
1063
+ const { format } = bundleConfig;
964
1064
  const { entries, pkg, exportPaths, cwd, tsOptions: { tsCompilerOptions }, pluginContext } = buildContext;
965
1065
  // Add esm mark and interop helper if esm export is detected
966
1066
  const useEsModuleMark = hasEsmExport(exportPaths, tsCompilerOptions);
967
- const absoluteOutputFile = path.resolve(cwd, options.file);
1067
+ const absoluteOutputFile = path.resolve(cwd, bundleConfig.file);
968
1068
  const name = filePathWithoutExtension(absoluteOutputFile);
969
1069
  var _exportCondition_export_types;
970
- const dtsFile = path.resolve(cwd, dts ? options.file : (_exportCondition_export_types = exportCondition.export.types) != null ? _exportCondition_export_types : getExportFileTypePath(options.file));
1070
+ const dtsFile = path.resolve(cwd, dts ? bundleConfig.file : (_exportCondition_export_types = exportCondition.export.types) != null ? _exportCondition_export_types : getExportFileTypePath(bundleConfig.file));
971
1071
  const typesDir = path.dirname(dtsFile);
972
1072
  const jsDir = path.dirname(absoluteOutputFile);
973
1073
  const outputFile = dts ? dtsFile : absoluteOutputFile;
974
1074
  const entryFiles = new Set(Object.values(entries).map((entry)=>entry.source));
975
- return {
1075
+ const inputOptions = await buildInputConfig(entry, bundleConfig, exportCondition, buildContext, dts);
1076
+ const outputOptions = {
976
1077
  name: pkg.name || name,
977
1078
  dir: dts ? typesDir : jsDir,
978
1079
  format,
@@ -981,7 +1082,7 @@ function buildOutputConfigs(options, exportCondition, buildContext, dts) {
981
1082
  interop: 'auto',
982
1083
  freeze: false,
983
1084
  strict: false,
984
- sourcemap: options.sourcemap,
1085
+ sourcemap: bundleConfig.sourcemap,
985
1086
  manualChunks: createSplitChunks(pluginContext.moduleDirectiveLayerMap, entryFiles),
986
1087
  chunkFileNames: '[name]-[hash].js',
987
1088
  // By default in rollup, when creating multiple chunks, transitive imports of entry chunks
@@ -989,19 +1090,24 @@ function buildOutputConfigs(options, exportCondition, buildContext, dts) {
989
1090
  hoistTransitiveImports: false,
990
1091
  entryFileNames: path.basename(outputFile)
991
1092
  };
1093
+ return {
1094
+ input: inputOptions,
1095
+ output: outputOptions
1096
+ };
992
1097
  }
993
1098
  async function buildEntryConfig(bundleConfig, pluginContext, dts) {
994
1099
  const configs = [];
995
1100
  const { entries } = pluginContext;
996
1101
  for (const exportCondition of Object.values(entries)){
997
- const rollupConfig = buildConfig(bundleConfig, exportCondition, pluginContext, dts);
998
- configs.push(rollupConfig);
1102
+ const rollupConfigs = await buildConfig(bundleConfig, exportCondition, pluginContext, dts);
1103
+ configs.push(...rollupConfigs);
999
1104
  }
1000
- return await Promise.all(configs);
1105
+ return configs;
1001
1106
  }
1002
1107
  async function collectEntry(// export type, e.g. react-server, edge-light those special cases required suffix
1003
1108
  exportType, options) {
1004
- const { cwd, pkg, entries, entryPath, exportCondRef, entryExport } = options;
1109
+ const { cwd, pkg, entries, entryPath, exportCondRef, entryExport: originEntryExport } = options;
1110
+ let entryExport = originEntryExport;
1005
1111
  let exportCondForType = {
1006
1112
  ...exportCondRef
1007
1113
  };
@@ -1010,8 +1116,13 @@ exportType, options) {
1010
1116
  exportCondForType = {
1011
1117
  [exportType]: exportCondRef[exportType]
1012
1118
  };
1013
- // Basic export type, pass down the exportPaths with erasing the special ones
1119
+ } else if (exportType[0] === '.' && suffixedExportConventions.has(exportType.slice(1))) {
1120
+ // e.g. .development, .production that has both esm and cjs export
1121
+ exportCondForType = exportCondRef;
1122
+ exportType = exportType.slice(1);
1123
+ entryExport = entryExport.replace(exportType, '');
1014
1124
  } else {
1125
+ // Basic export type, pass down the exportPaths with erasing the special ones
1015
1126
  for (const exportType of suffixedExportConventions){
1016
1127
  delete exportCondForType[exportType];
1017
1128
  }
@@ -1027,7 +1138,7 @@ exportType, options) {
1027
1138
  }
1028
1139
  const exportCondition = {
1029
1140
  source,
1030
- name: entryExport,
1141
+ name: originEntryExport,
1031
1142
  export: exportCondForType
1032
1143
  };
1033
1144
  const nameWithExportPath = pkg.name ? path__default.default.join(pkg.name, exportCondition.name) : exportCondition.name;
@@ -1089,6 +1200,8 @@ exportType, options) {
1089
1200
  for (const exportCondType of suffixedExportConventions){
1090
1201
  if (exportCond[exportCondType]) {
1091
1202
  await collectEntry(exportCondType, collectEntryOptions);
1203
+ } else if (entryExport === '.' + exportCondType) {
1204
+ await collectEntry(entryExport, collectEntryOptions);
1092
1205
  }
1093
1206
  }
1094
1207
  }
@@ -1098,14 +1211,8 @@ exportType, options) {
1098
1211
  }
1099
1212
  async function buildConfig(bundleConfig, exportCondition, pluginContext, dts) {
1100
1213
  const { file } = bundleConfig;
1101
- const { pkg, cwd, tsOptions } = pluginContext;
1102
- const useTypescript = Boolean(tsOptions.tsConfigPath);
1103
- const options = {
1104
- ...bundleConfig,
1105
- useTypescript
1106
- };
1214
+ const { pkg, cwd } = pluginContext;
1107
1215
  const entry = exportCondition.source;
1108
- const inputOptions = await buildInputConfig(entry, options, pluginContext, exportCondition, dts);
1109
1216
  const outputExports = getExportsDistFilesOfCondition(pkg, exportCondition, cwd);
1110
1217
  // If there's nothing found, give a default output
1111
1218
  if (outputExports.length === 0 && !pkg.bin) {
@@ -1149,26 +1256,18 @@ async function buildConfig(bundleConfig, exportCondition, pluginContext, dts) {
1149
1256
  bundleOptions = Array.from(uniqTypes).map((typeFile)=>{
1150
1257
  return {
1151
1258
  resolvedFile: typeFile,
1152
- format: 'es'
1259
+ format: 'esm'
1153
1260
  };
1154
1261
  });
1155
1262
  }
1156
- const outputConfigs = bundleOptions.map((bundleOption)=>{
1157
- return buildOutputConfigs({
1263
+ const outputConfigs = bundleOptions.map(async (bundleOption)=>{
1264
+ return await buildOutputConfigs(entry, {
1158
1265
  ...bundleConfig,
1159
1266
  file: bundleOption.resolvedFile,
1160
1267
  format: bundleOption.format
1161
1268
  }, exportCondition, pluginContext, dts);
1162
1269
  });
1163
- return {
1164
- input: inputOptions,
1165
- output: outputConfigs,
1166
- exportName: exportCondition.name || '.'
1167
- };
1168
- }
1169
-
1170
- function relativify(path) {
1171
- return path.startsWith('.') ? path : `./${path}`;
1270
+ return Promise.all(outputConfigs);
1172
1271
  }
1173
1272
 
1174
1273
  // Example: @foo/bar -> bar
@@ -1284,11 +1383,12 @@ function logOutputState(sizeCollector) {
1284
1383
  }).forEach((item, index)=>{
1285
1384
  const [filename, , size] = item;
1286
1385
  const normalizedExportName = normalizeExportName(exportName);
1287
- const prefix = index === 0 ? normalizedExportName + ' '.repeat(maxLengthOfExportName - normalizedExportName.length) : ' '.repeat(maxLengthOfExportName);
1288
- const sizePadding = ' '.repeat(maxFilenameLength - filename.length);
1289
- const prettiedSize = prettyBytes__default.default(size);
1386
+ const prefix = index === 0 ? normalizedExportName : ' '.repeat(normalizedExportName.length);
1387
+ const filenamePadding = ' '.repeat(Math.max(maxLengthOfExportName, 'Exports'.length) - normalizedExportName.length);
1290
1388
  const isType = isTypeFile(filename);
1291
- console.log(` ${prefix} ${pc[isType ? 'dim' : 'bold'](filename)}${sizePadding} ${prettiedSize}`);
1389
+ const sizePadding = ' '.repeat(Math.max(maxFilenameLength, 'File'.length) - filename.length);
1390
+ const prettiedSize = prettyBytes__default.default(size);
1391
+ console.log(prefix, filenamePadding, `${pc[isType ? 'dim' : 'bold'](filename)}`, sizePadding, prettiedSize);
1292
1392
  });
1293
1393
  });
1294
1394
  }
@@ -1357,9 +1457,9 @@ function hasMultiEntryExport(exportPaths) {
1357
1457
  const exportKeys = Object.keys(exportPaths).filter((key)=>key !== './package.json');
1358
1458
  return exportKeys.length > 0 && exportKeys.every((name)=>name.startsWith('.'));
1359
1459
  }
1360
- async function bundle(entryPath, { cwd: _cwd, ...options } = {}) {
1460
+ async function bundle(cliEntryPath, { cwd: _cwd, ...options } = {}) {
1361
1461
  const cwd = path.resolve(process.cwd(), _cwd || '');
1362
- assignDefault(options, 'format', 'es');
1462
+ assignDefault(options, 'format', 'esm');
1363
1463
  assignDefault(options, 'minify', false);
1364
1464
  assignDefault(options, 'target', 'es2015');
1365
1465
  const pkg = await getPackageMeta(cwd);
@@ -1369,6 +1469,7 @@ async function bundle(entryPath, { cwd: _cwd, ...options } = {}) {
1369
1469
  const isMultiEntries = hasMultiEntryExport(exportPaths) // exportPathsLength > 1
1370
1470
  ;
1371
1471
  const hasBin = Boolean(pkg.bin);
1472
+ const isFromCli = Boolean(cliEntryPath);
1372
1473
  let tsConfig = await resolveTsConfig(cwd);
1373
1474
  let hasTsConfig = Boolean(tsConfig == null ? void 0 : tsConfig.tsConfigPath);
1374
1475
  const defaultTsOptions = {
@@ -1379,10 +1480,10 @@ async function bundle(entryPath, { cwd: _cwd, ...options } = {}) {
1379
1480
  if (!isMultiEntries) {
1380
1481
  // Use specified string file path if possible, then fallback to the default behavior entry picking logic
1381
1482
  // e.g. "exports": "./dist/index.js" -> use "./index.<ext>" as entry
1382
- entryPath = entryPath || await getSourcePathFromExportPath(cwd, '.', 'default') || '';
1483
+ cliEntryPath = cliEntryPath || await getSourcePathFromExportPath(cwd, '.', 'default') || '';
1383
1484
  }
1384
1485
  // Handle CLI input
1385
- if (entryPath) {
1486
+ if (cliEntryPath) {
1386
1487
  let mainEntryPath;
1387
1488
  let typesEntryPath;
1388
1489
  // with -o option
@@ -1401,18 +1502,20 @@ async function bundle(entryPath, { cwd: _cwd, ...options } = {}) {
1401
1502
  }
1402
1503
  const bundleOrWatch = async (rollupConfig)=>{
1403
1504
  if (options.clean) {
1404
- await removeOutputDir(rollupConfig.output);
1505
+ if (!isFromCli) {
1506
+ await removeOutputDir(rollupConfig.output);
1507
+ }
1405
1508
  }
1406
1509
  if (options.watch) {
1407
1510
  return Promise.resolve(runWatch(rollupConfig));
1408
1511
  }
1409
1512
  return runBundle(rollupConfig);
1410
1513
  };
1411
- const hasSpecifiedEntryFile = entryPath ? fs__default.default.existsSync(entryPath) && (await fsp__default.default.stat(entryPath)).isFile() : false;
1514
+ const hasSpecifiedEntryFile = cliEntryPath ? fs__default.default.existsSync(cliEntryPath) && (await fsp__default.default.stat(cliEntryPath)).isFile() : false;
1412
1515
  const hasNoEntry = !hasSpecifiedEntryFile && !isMultiEntries && !hasBin;
1413
1516
  if (hasNoEntry) {
1414
- if (entryPath) {
1415
- const err = new Error(`Entry file "${entryPath}" does not exist`);
1517
+ if (cliEntryPath) {
1518
+ const err = new Error(`Entry file "${cliEntryPath}" does not exist`);
1416
1519
  err.name = 'NOT_EXISTED';
1417
1520
  return Promise.reject(err);
1418
1521
  } else if (cwd) {
@@ -1424,7 +1527,7 @@ async function bundle(entryPath, { cwd: _cwd, ...options } = {}) {
1424
1527
  }
1425
1528
  }
1426
1529
  }
1427
- const entries = await collectEntries(pkg, entryPath, exportPaths, cwd);
1530
+ const entries = await collectEntries(pkg, cliEntryPath, exportPaths, cwd);
1428
1531
  const hasTypeScriptFiles = Object.values(entries).some((entry)=>isTypescriptFile(entry.source));
1429
1532
  if (hasTypeScriptFiles && !hasTsConfig) {
1430
1533
  const tsConfigPath = path.resolve(cwd, 'tsconfig.json');
@@ -1497,15 +1600,11 @@ function runWatch({ input, output }) {
1497
1600
  return watcher;
1498
1601
  }
1499
1602
  async function removeOutputDir(output) {
1500
- const dirs = new Set(output.map(({ dir })=>dir));
1501
- for (const dir of dirs){
1502
- if (dir) await removeDir(dir);
1503
- }
1603
+ if (output.dir) await removeDir(output.dir);
1504
1604
  }
1505
1605
  function runBundle({ input, output }) {
1506
1606
  return rollup.rollup(input).then((bundle)=>{
1507
- const writeJobs = output.map((options)=>bundle.write(options));
1508
- return Promise.all(writeJobs);
1607
+ return bundle.write(output);
1509
1608
  }, catchErrorHandler);
1510
1609
  }
1511
1610
  function logError(error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunchee",
3
- "version": "4.4.0",
3
+ "version": "4.4.2",
4
4
  "description": "zero config bundler for js/ts/jsx libraries",
5
5
  "bin": "./dist/bin/cli.js",
6
6
  "main": "./dist/index.js",