-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
tree-shaking.ts
59 lines (53 loc) · 1.39 KB
/
tree-shaking.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { rollup, TreeshakingOptions, TreeshakingPreset } from 'rollup'
import hashbang from 'rollup-plugin-hashbang'
import { Plugin } from '../plugin'
export type TreeshakingStrategy =
| boolean
| TreeshakingOptions
| TreeshakingPreset
export const treeShakingPlugin = ({
treeshake,
}: {
treeshake?: TreeshakingStrategy
}): 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: [
hashbang(),
{
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',
})
const result = await bundle.generate({
format: this.format,
file: 'out.js',
sourcemap: !!this.options.sourcemap,
})
for (const file of result.output) {
if (file.type === 'chunk') {
if (file.fileName.endsWith('out.js')) {
return {
code: file.code,
map: file.map,
}
}
}
}
},
}
}