mirror of
https://github.com/egoist/tsup.git
synced 2025-12-08 20:35:58 +00:00
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import { rollup, type TreeshakingOptions, type TreeshakingPreset } from 'rollup'
|
|
import type { Plugin } from '../plugin'
|
|
|
|
export type TreeshakingStrategy =
|
|
| boolean
|
|
| TreeshakingOptions
|
|
| TreeshakingPreset
|
|
|
|
export const treeShakingPlugin = ({
|
|
treeshake,
|
|
name,
|
|
silent,
|
|
}: {
|
|
treeshake?: TreeshakingStrategy
|
|
name?: string
|
|
silent?: boolean
|
|
}): Plugin => {
|
|
return {
|
|
name: 'tree-shaking',
|
|
|
|
async renderChunk(code, info) {
|
|
if (!treeshake || !/\.(cjs|js|mjs)$/.test(info.path)) return
|
|
|
|
const bundle = await rollup({
|
|
input: [info.path],
|
|
plugins: [
|
|
{
|
|
name: 'tsup',
|
|
resolveId(source) {
|
|
if (source === info.path) return source
|
|
return false
|
|
},
|
|
load(id) {
|
|
if (id === info.path) return code
|
|
},
|
|
},
|
|
],
|
|
treeshake: treeshake,
|
|
makeAbsoluteExternalsRelative: false,
|
|
preserveEntrySignatures: 'exports-only',
|
|
onwarn: silent ? () => {} : undefined,
|
|
})
|
|
|
|
const result = await bundle.generate({
|
|
interop: 'auto',
|
|
format: this.format,
|
|
file: 'out.js',
|
|
sourcemap: !!this.options.sourcemap,
|
|
name,
|
|
})
|
|
|
|
for (const file of result.output) {
|
|
if (file.type === 'chunk') {
|
|
if (file.fileName.endsWith('out.js')) {
|
|
return {
|
|
code: file.code,
|
|
map: file.map,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
},
|
|
}
|
|
}
|