-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
register.ts
66 lines (61 loc) · 2.06 KB
/
register.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
import { platform } from 'os'
import { resolve } from 'path'
import { transformSync } from '@swc-node/core'
import { SourcemapMap, installSourceMapSupport } from '@swc-node/sourcemap-support'
import { addHook } from 'pirates'
import * as ts from 'typescript'
import { readDefaultTsConfig, tsCompilerOptionsToSwcConfig } from './read-default-tsconfig'
const DEFAULT_EXTENSIONS = ['.js', '.jsx', '.es6', '.es', '.mjs', '.ts', '.tsx']
const PLATFORM = platform()
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
) {
if (filename.endsWith('.d.ts')) {
return ''
}
if (options.files && (options.files as string[]).length) {
if (
PLATFORM === 'win32' &&
(options.files as string[]).every((file) => filename !== resolve(process.cwd(), file))
) {
return sourcecode
}
if (PLATFORM !== 'win32' && (options.files as string[]).every((file) => !filename.endsWith(file))) {
return sourcecode
}
}
if (options && typeof options.fallbackToTs === 'function' && options.fallbackToTs(filename)) {
delete options.fallbackToTs
const { outputText, sourceMapText } = ts.transpileModule(sourcecode, {
fileName: filename,
compilerOptions: options,
})
if (sourceMapText) {
SourcemapMap.set(filename, sourceMapText)
}
return outputText
} else {
const swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename)
if (process.env.SWCRC === 'true') {
// when SWCRC environment variable is set to true it will use swcrc file
swcRegisterConfig.swc = {
swcrc: true,
}
}
const { code, map } = transformSync(sourcecode, filename, swcRegisterConfig)
// in case of map is undefined
if (map) {
SourcemapMap.set(filename, map)
}
return code
}
}
export function register(options = readDefaultTsConfig(), hookOpts = {}) {
installSourceMapSupport()
return addHook((code, filename) => compile(code, filename, options), {
exts: DEFAULT_EXTENSIONS,
...hookOpts,
})
}