1
+ import type { Plugin } from 'rollup'
2
+ // @ts -expect-error Cannot find module 'load-tsconfig' or its corresponding type declarations.ts(2307)
3
+ import { loadTsConfig } from 'load-tsconfig'
4
+ import { Options as SWCOptions , transform } from '@swc/core'
5
+ import extend from '@techor/extend'
6
+ import { FilterPattern , createFilter } from '@rollup/pluginutils'
7
+
8
+ export type Options = SWCOptions & {
9
+ include ?: FilterPattern
10
+ exclude ?: FilterPattern
11
+ tsconfigFile ?: string | boolean
12
+ }
13
+
14
+ export default function swc ( { tsconfigFile, include, exclude, minify, ...options } : Options = { } ) : Plugin {
15
+ const filter = createFilter ( include , exclude )
16
+ const compilerOptions = tsconfigFile === false ? { } : loadTsConfig ( '.' , tsconfigFile === true ? undefined : tsconfigFile ) ?. data ?. compilerOptions || { }
17
+ let swcOptions = {
18
+ jsc : {
19
+ target : compilerOptions . target ,
20
+ parser : { } ,
21
+ transform : { }
22
+ }
23
+ } as SWCOptions
24
+ if ( compilerOptions . experimentalDecorators ) {
25
+ swcOptions . jsc . parser . decorators = true
26
+ swcOptions . jsc . transform . legacyDecorator = true
27
+ swcOptions . jsc . transform . decoratorMetadata = compilerOptions . emitDecoratorMetadata
28
+ }
29
+ if ( compilerOptions . jsx ) {
30
+ swcOptions . jsc . transform . react = {
31
+ pragma : compilerOptions . jsxFactory ,
32
+ pragmaFrag : compilerOptions . jsxFragmentFactory ,
33
+ importSource : compilerOptions . jsxImportSource ,
34
+ }
35
+ }
36
+ swcOptions = extend ( swcOptions , options )
37
+ return {
38
+ name : 'techor-swc' ,
39
+ async transform ( code , id ) {
40
+ if ( ! filter ( id ) ) return null
41
+ const transformed = await transform ( code , {
42
+ filename : id ,
43
+ sourceMaps : true ,
44
+ ...extend ( swcOptions , {
45
+ jsc : {
46
+ parser : / \. t s ? $ / . test ( id )
47
+ ? { syntax : 'typescript' , tsx : / \. t s x $ / . test ( id ) }
48
+ : { syntax : 'ecmascript' , jsx : / \. j s x $ / . test ( id ) }
49
+ }
50
+ } as SWCOptions )
51
+ } )
52
+ return {
53
+ code : transformed . code ,
54
+ map : transformed . map && JSON . parse ( transformed . map ) ,
55
+ }
56
+ } ,
57
+ async renderChunk ( code , chunk ) {
58
+ return minify
59
+ ? await transform ( code , {
60
+ ...swcOptions ,
61
+ sourceMaps : true ,
62
+ minify : true ,
63
+ filename : chunk . fileName ,
64
+ } )
65
+ : null
66
+ }
67
+ } as Plugin
68
+ }
0 commit comments