getBaseConfig.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { env } from "node:process";
  2. import browsersListToEsBuild from "browserslist-to-esbuild";
  3. import { Format, Options } from "tsup";
  4. import { DevFlagPlugin } from "./dev-flag";
  5. type Platform =
  6. | "browser"
  7. // React Native
  8. | "native"
  9. | "node";
  10. const BROWSERSLIST_TARGETS = browsersListToEsBuild();
  11. export function getBaseConfig(
  12. platform: Platform,
  13. formats: Format[],
  14. optionsInput: Options,
  15. ): Options[] {
  16. return [true, false]
  17. .flatMap<Options | null>((isDebugBuild) =>
  18. formats.map((format) =>
  19. format !== "iife" && isDebugBuild
  20. ? null // We don't build debug builds for packages; only for the iife bundle.
  21. : {
  22. define: {
  23. __BROWSER__: `${platform === "browser"}`,
  24. __NODEJS__: `${platform === "node"}`,
  25. __REACTNATIVE__: `${platform === "native"}`,
  26. __VERSION__: `"${env.npm_package_version}"`,
  27. },
  28. entry: optionsInput.entry
  29. ? optionsInput.entry
  30. : [`./src/index.ts`],
  31. esbuildOptions(options, context) {
  32. const { format } = context;
  33. options.minify = format === "iife" && !isDebugBuild;
  34. if (format === "iife") {
  35. options.define = {
  36. ...options.define,
  37. __DEV__: `${isDebugBuild}`,
  38. };
  39. options.target = BROWSERSLIST_TARGETS;
  40. } else {
  41. options.define = {
  42. ...options.define,
  43. // Preserve `process.env.NODE_ENV` in the output without
  44. // replacing it. This allows consumers' bundlers to replace it
  45. // as they see fit.
  46. "process.env.NODE_ENV": "process.env.NODE_ENV",
  47. };
  48. }
  49. },
  50. esbuildPlugins: [DevFlagPlugin],
  51. format,
  52. globalName: "globalThis.gill",
  53. name: platform,
  54. outExtension({ format }) {
  55. let extension;
  56. if (format === "iife") {
  57. extension = `.${
  58. isDebugBuild ? "development" : "production.min"
  59. }.js`;
  60. } else {
  61. extension = `.${platform}.${
  62. format === "cjs" ? "cjs" : "mjs"
  63. }`;
  64. }
  65. return {
  66. js: extension,
  67. };
  68. },
  69. platform: platform === "node" ? "node" : "browser",
  70. pure: ["process"],
  71. sourcemap: format !== "iife" || isDebugBuild,
  72. treeshake: true,
  73. },
  74. ),
  75. )
  76. .filter(Boolean) as Options[];
  77. }