fix: preserve top-level when running terser for IIFE (#900)

Co-authored-by: EGOIST <hi@egoist.dev>
This commit is contained in:
翠 / green 2023-06-16 15:39:01 +09:00 committed by GitHub
parent 2f41663dc2
commit 2c0435a30f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 14 deletions

View File

@ -262,6 +262,7 @@ export async function build(_options: Options) {
minifyOptions: options.minify,
format,
terserOptions: options.terserOptions,
globalName: options.globalName,
logger,
}),
])

View File

@ -9,11 +9,13 @@ export const terserPlugin = ({
minifyOptions,
format,
terserOptions = {},
logger
globalName,
logger,
}: {
minifyOptions: Options['minify']
format: Format
terserOptions?: MinifyOptions,
terserOptions?: MinifyOptions
globalName?: string
logger: Logger
}): Plugin => {
return {
@ -37,7 +39,7 @@ export const terserPlugin = ({
if (format === 'esm') {
defaultOptions.module = true
} else {
} else if (!(format === 'iife' && globalName !== undefined)) {
defaultOptions.toplevel = true
}

View File

@ -1255,12 +1255,10 @@ test(`should generate export {} when there are no exports in source file`, async
})
test('custom inject style function', async () => {
const { outFiles, getFileContent } = await run(
getTestName(),
{
'input.ts': `import './style.css'`,
'style.css': `.hello { color: red }`,
'tsup.config.ts': `
const { outFiles, getFileContent } = await run(getTestName(), {
'input.ts': `import './style.css'`,
'style.css': `.hello { color: red }`,
'tsup.config.ts': `
export default {
entry: ['src/input.ts'],
minify: true,
@ -1269,13 +1267,30 @@ test('custom inject style function', async () => {
return "__custom_inject_style__(" + css +")";
}
}`,
},
)
})
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`)')
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`)'
)
})
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*=/)
})
test('should load postcss esm config', async () => {
const { outFiles, getFileContent } = await run(getTestName(), {
@ -1301,4 +1316,4 @@ test('should load postcss esm config', async () => {
expect(outFiles).toEqual(['input.cjs', 'input.css'])
expect(await getFileContent('dist/input.css')).toContain('color: blue;')
})
})