-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathvite.swc.ts
94 lines (82 loc) · 2.43 KB
/
vite.swc.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
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
93
94
/**
* Copyright (c) Statsify
*
* This source code is licensed under the GNU GPL v3 license found in the
* LICENSE file in the root directory of this source tree.
* https://github.com/Statsify/statsify/blob/main/LICENSE
*/
/**
* Adapted from: https://github.com/egoist/unplugin-swc
* because the module does not work with ESM
*/
import { Options as SwcOptions, transform } from "@swc/core";
import { createFilter } from "@rollup/pluginutils";
import { createUnplugin } from "unplugin";
import { dirname, join, resolve } from "node:path";
import { existsSync } from "node:fs";
import { stat } from "node:fs/promises";
const RESOLVE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".cjs"];
const resolveFile = (resolved: string, index = false) => {
for (const ext of RESOLVE_EXTENSIONS) {
const file = index ? join(resolved, `index${ext}`) : `${resolved}${ext}`;
if (existsSync(file)) return file;
}
};
export const resolveId = async (importee: string, importer?: string) => {
if (importer && importee[0] === ".") {
const absolutePath = resolve(importer ? dirname(importer) : process.cwd(), importee);
let resolved = resolveFile(absolutePath);
if (
!resolved &&
existsSync(absolutePath) &&
(await stat(absolutePath).then((stat) => stat.isDirectory()))
) {
resolved = resolveFile(absolutePath, true);
}
return resolved;
}
};
export const swc = createUnplugin(({ minify, ...options }: SwcOptions = {}) => {
const filter = createFilter(/\.[jt]sx?$/, /node_modules/);
if (options.jsc?.transform?.optimizer?.globals?.vars) {
delete options.jsc.transform.optimizer.globals.vars["import.meta.vitest"];
}
return {
name: "swc",
resolveId,
async transform(code, id) {
if (!filter(id)) return null;
const result = await transform(code, {
filename: id,
...options,
});
return {
code: result.code,
map: result.map && JSON.parse(result.map),
};
},
vite: {
config() {
return {
esbuild: false,
};
},
},
rollup: {
async renderChunk(code, chunk) {
if (minify) {
const result = await transform(code, {
sourceMaps: true,
minify: true,
filename: chunk.fileName,
});
return {
code: result.code,
map: result.map,
};
}
return null;
},
},
};
});