Skip to content

Commit 2ec327b

Browse files
committed
refactor: module transpiler
1 parent 46935ac commit 2ec327b

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/core/next.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,20 @@ async function safeEval(code: string, routePath: string) {
3333
}
3434
}
3535

36+
async function getModuleTranspiler() {
37+
if (typeof require === "undefined") {
38+
const { transpileModule } = await import(/* webpackIgnore: true */ "typescript");
39+
return transpileModule;
40+
}
41+
// eslint-disable-next-line @typescript-eslint/no-require-imports
42+
return require(/* webpackIgnore: true */ "typescript").transpileModule;
43+
}
44+
3645
export async function getRouteExports(routePath: string, routeDefinerName: string, schemas: Record<string, unknown>) {
3746
const rawCode = await fs.readFile(routePath, "utf-8");
3847
const middlewareName = detectMiddlewareName(rawCode);
3948
const isCommonJS = typeof module !== "undefined" && typeof module.exports !== "undefined";
40-
const { transpileModule } = await import(/* webpackIgnore: true */ "typescript");
41-
const code = transpile(isCommonJS, rawCode, middlewareName, transpileModule);
49+
const code = transpile(isCommonJS, rawCode, middlewareName, await getModuleTranspiler());
4250
const fixedCode = Object.keys(schemas).reduce(injectSchemas, code);
4351
(global as Record<string, unknown>)[routeDefinerName] = defineRoute;
4452
(global as Record<string, unknown>).z = z;

src/core/transpile.test.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
import { transpileModule } from "typescript";
12
import { describe, expect, it } from "vitest";
23
import { transpile } from "./transpile";
34

45
describe("transpile", () => {
56
it("should inject export fixers", () => {
6-
const result = transpile(true, "", null);
7+
const result = transpile(true, "", null, transpileModule);
78
expect(result).toContain("exports.GET = void 0;");
89
expect(result).toContain("exports.POST = void 0;");
910
expect(result).toContain("exports.PUT = void 0;");
@@ -14,7 +15,7 @@ describe("transpile", () => {
1415
});
1516

1617
it("should inject a placeholder function for the middleware", () => {
17-
const result = transpile(true, "", "myAwesomeMiddleware");
18+
const result = transpile(true, "", "myAwesomeMiddleware", transpileModule);
1819
expect(result).toContain("const myAwesomeMiddleware = (handler) => handler;");
1920
});
2021
});

0 commit comments

Comments
 (0)