/
index.ts
69 lines (63 loc) · 1.69 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
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
import { transformSync, TransformResult } from "esbuild";
import { transformRequire, isCommonJS } from "./lib";
import * as fs from "fs";
import { Plugin } from "vite";
import createFilter from "./filter";
export type Options = {
include?: string | string[] | undefined;
exclude?: string | string[] | undefined;
skipPreBuild?: boolean;
};
export function viteCommonjs(
options: Options = { skipPreBuild: false }
): Plugin {
const filter = createFilter(options.include, options.exclude);
return {
name: "originjs:commonjs",
apply: "serve",
transform(code: string, id: string): TransformResult {
if (
!filter(id) ||
(options.skipPreBuild && id.indexOf("/node_modules/.vite/") !== -1)
) {
return null;
}
let result = transformRequire(code, id);
if (id.indexOf("/node_modules/.vite/") == -1 && isCommonJS(code)) {
return transformSync(result.code, { format: "esm" });
}
if (result.replaced) {
return {
code: result.code,
map: null,
warnings: null,
};
}
return null;
},
};
}
export function esbuildCommonjs(include: string[] = []) {
return {
name: "originjs:commonjs",
setup(build) {
build.onLoad(
{
filter: new RegExp("(" + include.join("|") + ").*.js"),
namespace: "file",
},
async ({ path: id }) => {
const code = fs.readFileSync(id).toString();
let result = transformRequire(code, id);
if (result.replaced) {
return {
contents: result.code,
loader: "js",
};
}
return null;
}
);
},
};
}