-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
44 lines (36 loc) · 1.37 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
import typescript, { CompilerOptions } from 'typescript';
export function vitePluginTypescriptTranspile({ fileRegex = /\.ts$/, cwd = process.cwd(), compilerOverrides = {
inlineSources: true,
inlineSourceMap: true,
sourceMap: false,
moduleResolution: typescript.ModuleResolutionKind.Bundler,
module: typescript.ModuleKind.ES2022
} }: { fileRegex?: RegExp, cwd?: string; compilerOverrides?: CompilerOptions }) {
const fileName = typescript.findConfigFile(cwd, typescript.sys.fileExists);
if (!fileName) throw 'tsconfig.json not found!';
const text = typescript.sys.readFile(fileName);
if (text === undefined) throw new Error(`failed to read '${fileName}'`);
const result = typescript.parseConfigFileTextToJson(fileName, text);
if (result.error !== undefined)
throw new Error(`failed to parse '${fileName}'`);
const parsedTsConfig = typescript.parseJsonConfigFileContent(result.config, typescript.sys, cwd);
const compilerOptions: CompilerOptions = {
...parsedTsConfig.options,
...compilerOverrides
}
return {
name: 'typescript-transpile',
transform(src: string, id: string) {
if (fileRegex.test(id)) {
const program = typescript.transpileModule(src, {
compilerOptions,
fileName: id
});
return {
code: program.outputText,
map: program.sourceMapText
};
}
}
};
}