From dba3cf8e0f96d6ed191e3d816c3db882070c3418 Mon Sep 17 00:00:00 2001 From: sapphi-red <49056869+sapphi-red@users.noreply.github.com> Date: Fri, 5 May 2023 17:38:50 +0900 Subject: [PATCH] fix: preserve top-level when running terser for IIFE --- src/index.ts | 1 + src/plugins/terser.ts | 6 ++++-- test/index.test.ts | 17 ++++++++++++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index 64e062d2..ffb09f70 100644 --- a/src/index.ts +++ b/src/index.ts @@ -265,6 +265,7 @@ export async function build(_options: Options) { minifyOptions: options.minify, format, terserOptions: options.terserOptions, + globalName: options.globalName, }), ]) await runEsbuild(options, { diff --git a/src/plugins/terser.ts b/src/plugins/terser.ts index 78168ace..04172546 100644 --- a/src/plugins/terser.ts +++ b/src/plugins/terser.ts @@ -11,10 +11,12 @@ export const terserPlugin = ({ minifyOptions, format, terserOptions = {}, + globalName }: { minifyOptions: Options['minify'] format: Format - terserOptions?: MinifyOptions + terserOptions?: MinifyOptions, + globalName?: string }): Plugin => { return { name: 'terser', @@ -37,7 +39,7 @@ export const terserPlugin = ({ if (format === 'esm') { defaultOptions.module = true - } else { + } else if (!(format === 'iife' && globalName !== undefined)) { defaultOptions.toplevel = true } diff --git a/test/index.test.ts b/test/index.test.ts index 9e7c71e8..8c83be38 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1266,4 +1266,19 @@ test('custom inject style function', async () => { expect(outFiles).toEqual(['input.js', 'input.mjs']) expect(await getFileContent('dist/input.mjs')).toContain('__custom_inject_style__(`.hello{color:red}\n`)') expect(await getFileContent('dist/input.js')).toContain('__custom_inject_style__(`.hello{color:red}\n`)') -}) \ No newline at end of file +}) + +test('preserve top-level variable for IIFE format', async () => { + const { outFiles, getFileContent } = await run(getTestName(), { + 'input.ts': `export default 'foo'`, + 'tsup.config.ts': ` + export default { + entry: ['src/input.ts'], + globalName: 'globalFoo', + minify: 'terser', + format: ['iife'] + }`, + }) + expect(outFiles).toEqual(['input.global.js']) + expect(await getFileContent('dist/input.global.js')).toMatch(/globalFoo\s*=/) +})