-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathindex.ts
64 lines (52 loc) · 1.6 KB
/
index.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
import { Format, Loader, transformSync } from 'esbuild'
import path, { extname } from 'path'
const getExt = (str: string) => {
const basename = path.basename(str);
const firstDot = basename.indexOf('.');
const lastDot = basename.lastIndexOf('.');
const extname = path.extname(basename).replace(/(\.[a-z0-9]+).*/i, '$1');
if (firstDot === lastDot) return extname
return basename.slice(firstDot, lastDot) + extname;
}
const getOptions = (config: any) => {
let options = {}
for (let i = 0; i < config.transform.length; i++) {
options = config.transform[i][2]
}
return options
}
export interface Options {
jsxFactory?: string
jsxFragment?: string
sourcemap?: boolean | 'inline' | 'external'
loaders?: {
[ext: string]: Loader
},
target?: string
format?: string
}
export function process(content: string, filename: string, config: any) {
const options: Options = getOptions(config)
const ext = getExt(filename)
const loader = options?.loaders && options?.loaders[ext]
? options.loaders[ext]
: extname(filename).slice(1) as Loader
const sourcemaps = options?.sourcemap
? { sourcemap: true, sourcefile: filename }
: {}
const result = transformSync(content, {
loader,
format: options?.format as Format || 'cjs',
target: options?.target || 'es2018',
...(options?.jsxFactory ? { jsxFactory: options.jsxFactory }: {}),
...(options?.jsxFragment ? { jsxFragment: options.jsxFragment }: {}),
...sourcemaps
})
return {
code: result.code,
map: result?.map ? {
...JSON.parse(result.map),
sourcesContent: null,
}: ''
}
}