Skip to content

Commit

Permalink
fix: now working as a loader
Browse files Browse the repository at this point in the history
  • Loading branch information
marco-ippolito committed Aug 7, 2024
1 parent aa480d2 commit 1f97f37
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 24 deletions.
7 changes: 0 additions & 7 deletions .swcrc

This file was deleted.

5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,5 @@
"rimraf": "^6.0.1",
"typescript": "^5.5.3"
},
"files": [
"dist",
"LICENSE.md"
]
"files": ["dist", "LICENSE.md"]
}
31 changes: 21 additions & 10 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import swc from "../lib/wasm.js";
import type { LoadHook } from "node:module";
import { readFile } from "node:fs/promises";
import type { LoadFnOutput, LoadHookContext } from "node:module";
import { transformSync } from "./index.ts";

export const load: LoadHook = async (source, context, nextLoad) => {
if (context.format?.includes("typescript")) {
const data = await readFile(source, "utf8");
type NextLoad = (
url: string,
context?: LoadHookContext,
) => LoadFnOutput | Promise<LoadFnOutput>;

export async function load(
url: string,
context: LoadHookContext,
nextLoad: NextLoad,
) {
const { format } = context;
if (format.includes("typescript")) {
const { source = "" } = await nextLoad(url, context);
const { code } = transformSync(source.toString(), { mode: "transform" });
return {
source: swc.transformSync(data).code,
shortCircuit: true, // Skips bundled transpilation
format: format.replace("-typescript", ""),
source: code,
shortCircuit: true,
};
}
return { source: await nextLoad(source, context) };
};
return { source: await nextLoad(url, context) };
}
2 changes: 1 addition & 1 deletion test/fixtures/enum.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
enum Foo {
A = "Hello, TypeScript!"
A = "Hello, TypeScript!",
}
console.log(Foo.A);
4 changes: 2 additions & 2 deletions test/loader.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ test("should work as a loader", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/index.js",
"--loader=./dist/index.js",
fixturesPath("hello.ts"),
]);

Expand All @@ -19,7 +19,7 @@ test("should work with enums", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/index.js",
"--loader=./dist/index.js",
fixturesPath("enum.ts"),
]);

Expand Down

0 comments on commit 1f97f37

Please sign in to comment.