tsup.config.base.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { env } from 'node:process';
  2. import browsersListToEsBuild from 'browserslist-to-esbuild';
  3. import { Format, Options as TsupConfig } from 'tsup';
  4. type Platform = 'browser' | 'node' | 'react-native';
  5. type BuildOptions = {
  6. format: Format;
  7. platform: Platform;
  8. };
  9. const BROWSERSLIST_TARGETS = browsersListToEsBuild();
  10. export function getBuildConfig(options: BuildOptions): TsupConfig {
  11. const { format, platform } = options;
  12. return {
  13. define: {
  14. __BROWSER__: `${platform === 'browser'}`,
  15. __ESM__: `${format === 'esm'}`,
  16. __NODEJS__: `${platform === 'node'}`,
  17. __REACTNATIVE__: `${platform === 'react-native'}`,
  18. __TEST__: 'false',
  19. __VERSION__: `"${env.npm_package_version}"`,
  20. },
  21. entry: [`./src/index.ts`],
  22. esbuildOptions(options, context) {
  23. if (context.format === 'iife') {
  24. options.target = BROWSERSLIST_TARGETS;
  25. options.minify = true;
  26. } else {
  27. options.define = {
  28. ...options.define,
  29. 'process.env.NODE_ENV': 'process.env.NODE_ENV',
  30. };
  31. }
  32. },
  33. external: ['node:fs', 'node:path', 'node:url'],
  34. format,
  35. globalName: 'globalThis.codama',
  36. name: platform,
  37. // Inline private, non-published packages.
  38. // WARNING: This inlines packages recursively. Make sure these don't have deep dep trees.
  39. noExternal: [
  40. // @noble/hashes/sha256 is an ESM-only module, so we have to inline it in CJS builds.
  41. ...(format === 'cjs' ? ['@noble/hashes/sha256', '@noble/hashes/crypto'] : []),
  42. ],
  43. outExtension({ format }) {
  44. const extension =
  45. format === 'iife' ? `.production.min.js` : `.${platform}.${format === 'cjs' ? 'cjs' : 'mjs'}`;
  46. return { js: extension };
  47. },
  48. platform: platform === 'node' ? 'node' : 'browser',
  49. publicDir: true,
  50. pure: ['process'],
  51. sourcemap: format !== 'iife',
  52. // Treeshaking already happens with esbuild but tsup offers this options
  53. // for "better" treeshaking strategies using Rollup as an additional step.
  54. // The issue is Rollup now uses the deprecated "assert" import keyword by default
  55. // And tsup doesn't offer a way to change this behavior. Since the CLI package
  56. // relies on using the "with" keyword to dynamically import JSON files,
  57. // we can't use Rollup for treeshaking.
  58. treeshake: false,
  59. };
  60. }