diff --git a/packages/typescript-async-loaders/README.md b/packages/typescript-async-loaders/README.md new file mode 100644 index 0000000..371c6d4 --- /dev/null +++ b/packages/typescript-async-loaders/README.md @@ -0,0 +1,5 @@ +## TypeScript and async custom loaders + +Mocha 11.7.0 added support for Node's experimental [`require_module`](https://nodejs.org/docs/v22.20.0/api/modules.html#loading-ecmascript-modules-using-require) feature, which makes file loading a bit more complicated for Mocha 11. In this example, we showcase using ts-node **and** a custom asynchronous module loader to run a TypeScript test file. + +This example shows more integrations than what most projects need. For a more straightforward example, see the [`typescript`](../typescript) sibling package. diff --git a/packages/typescript-async-loaders/custom-loader.mjs b/packages/typescript-async-loaders/custom-loader.mjs new file mode 100644 index 0000000..3351ae8 --- /dev/null +++ b/packages/typescript-async-loaders/custom-loader.mjs @@ -0,0 +1,7 @@ +export async function load(url, context, defaultLoad) { + if (url.endsWith(".ts")) { + console.log("Loaded with custom loader"); + await new Promise((resolve) => setTimeout(resolve, 1)); + } + return defaultLoad(url, context, defaultLoad); +} diff --git a/packages/typescript-async-loaders/package.json b/packages/typescript-async-loaders/package.json new file mode 100644 index 0000000..1963bf7 --- /dev/null +++ b/packages/typescript-async-loaders/package.json @@ -0,0 +1,17 @@ +{ + "name": "example-typescript-async-loaders", + "version": "1.0.0", + "type": "module", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "scripts": { + "test": "NODE_OPTIONS='--loader=ts-node/esm --loader=./custom-loader.mjs' mocha test/**/*.test.ts" + }, + "devDependencies": { + "mocha": "^11.7.0", + "ts-node": "^10.9.0", + "typescript": "^5.0.0", + "@types/mocha": "^10.0.0" + } +} diff --git a/packages/typescript-async-loaders/test/async-loader.test.ts b/packages/typescript-async-loaders/test/async-loader.test.ts new file mode 100644 index 0000000..3f4feb4 --- /dev/null +++ b/packages/typescript-async-loaders/test/async-loader.test.ts @@ -0,0 +1,12 @@ +import assert from "assert"; +import { describe, it } from "mocha"; + +function add(a: number, b: number): number { + return a + b; +} + +describe("async loaders", () => { + it("should work", () => { + assert.strictEqual(add(2, 3), 5); + }); +});