// Inspired by https://github.com/remanufacturing/react-truncate/blob/0ed69b87021e937c7768dcfee29c0289b2153788/tsup.config.ts import { type Options } from 'tsup'; type ESBuildPlugin = NonNullable[number]; export const NAMESPACE = '@preserves/iifeExternalPlugin'; // NB. Make sure the keys of `Externals` do not contain any RegExp metacharacters! // RegExp.escape() is missing in node.js as of this writing :-( // // Keys are module import paths, values are global variable names. // export type Externals = Record; export function withIifeExternalPlugin(externals: Externals, options: Options): Options { return { ... options, esbuildOptions(inner, context) { options.esbuildOptions?.(inner, context); (inner.external ??= []).push(... Object.keys(externals)); }, esbuildPlugins: [... (options.esbuildPlugins ?? []), iifeExternalPlugin(externals)], }; } export function iifeExternalPlugin(externals: Externals): ESBuildPlugin { const filter = new RegExp(`^(${Object.keys(externals).join('|')})$`); return { name: NAMESPACE, setup(build) { build.onResolve({ filter }, args => ({ path: args.path, namespace: NAMESPACE })); build.onLoad({ filter: /.*/, namespace: NAMESPACE }, args => ({ contents: `module.exports = ${externals[args.path]}` })); }, }; }