forked from egoist/tsup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swc-target.ts
69 lines (62 loc) · 1.75 KB
/
swc-target.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
60
61
62
63
64
65
66
67
68
69
import type { ModuleConfig } from '@swc/core/types';
import { PrettyError } from '../errors'
import { Plugin } from '../plugin'
import { localRequire } from '../utils'
const TARGETS = ['es5', 'es3'] as const
export const swcTarget = (): Plugin => {
let enabled = false
let target: typeof TARGETS[number]
return {
name: 'swc-target',
esbuildOptions(options) {
if (
typeof options.target === 'string' &&
TARGETS.includes(options.target as any)
) {
target = options.target as any
options.target = 'es2020'
enabled = true
}
},
async renderChunk(code, info) {
if (!enabled || !/\.(cjs|mjs|js)$/.test(info.path)) {
return
}
const swc: typeof import('@swc/core') = localRequire('@swc/core')
if (!swc) {
throw new PrettyError(
`@swc/core is required for ${target} target. Please install it with \`npm install @swc/core -D\``
)
}
const result = await swc.transform(code, {
filename: info.path,
sourceMaps: this.options.sourcemap,
minify: Boolean(this.options.minify),
jsc: {
target,
parser: {
syntax: 'ecmascript',
},
minify:
this.options.minify === true
? {
compress: false,
mangle: {
reserved: this.options.globalName
? [this.options.globalName]
: [],
},
}
: undefined,
},
module: {
type: this.format === 'cjs' ? 'commonjs' : 'es6'
} as ModuleConfig,
})
return {
code: result.code,
map: result.map,
}
},
}
}