This repository was archived by the owner on Jan 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathcompile.ts
More file actions
92 lines (81 loc) · 2.09 KB
/
compile.ts
File metadata and controls
92 lines (81 loc) · 2.09 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import slash from "slash";
import { promises } from "fs";
import { dirname, relative } from "path";
import { transformFile, transformFileSync } from "@swc/core";
import type { Options, Output } from "@swc/core";
const { mkdir, stat, writeFile } = promises;
function withSourceMap(
output: Output,
options: Options,
destFile: string,
destDir: string
) {
if (!output.map || options.sourceMaps === "inline") {
return {
sourceCode: output.code,
};
}
// TODO: remove once fixed in core https://github.com/swc-project/swc/issues/1388
const sourceMap = JSON.parse(output.map);
if (options.sourceFileName) {
sourceMap["sources"][0] = options.sourceFileName;
}
if (options.sourceRoot) {
sourceMap["sourceRoot"] = options.sourceRoot;
}
output.map = JSON.stringify(sourceMap);
const sourceMapPath = destFile + ".map";
output.code += `\n//# sourceMappingURL=${slash(
relative(destDir, sourceMapPath)
)}`;
return {
sourceMap: output.map,
sourceMapPath,
sourceCode: output.code,
};
}
export async function outputResult(
output: Output,
sourceFile: string,
destFile: string,
options: Options
) {
const destDir = dirname(destFile);
const { sourceMap, sourceMapPath, sourceCode } = withSourceMap(
output,
options,
destFile,
destDir
);
await mkdir(destDir, { recursive: true });
const { mode } = await stat(sourceFile);
if (!sourceMapPath) {
await writeFile(destFile, sourceCode, { mode });
} else {
await Promise.all([
writeFile(destFile, sourceCode, { mode }),
writeFile(sourceMapPath, sourceMap, { mode }),
]);
}
}
export async function compile(
filename: string,
opts: Options,
sync: boolean,
outputPath: string | undefined
): Promise<Output | void> {
const options = { ...opts };
if (outputPath) {
options.outputPath = outputPath;
}
try {
const result = sync
? transformFileSync(filename, options)
: await transformFile(filename, options);
return result;
} catch (err: any) {
if (!err.message.includes("ignored by .swcrc")) {
throw err;
}
}
}