diff --git a/lib/loader.spec.ts b/lib/loader.spec.ts index bcde7fc..f0a1f25 100644 --- a/lib/loader.spec.ts +++ b/lib/loader.spec.ts @@ -9,12 +9,13 @@ describe("TypeScriptLoader", () => { const fixturesPath = path.resolve(__dirname, "__fixtures__"); let loader: Loader; + let tsNodeSpy = jest.spyOn(tsnode, "register"); function readFixtureContent(file: string): string { return fs.readFileSync(file).toString(); } - beforeEach(() => { + beforeAll(() => { loader = TypeScriptLoader(); }); @@ -28,6 +29,14 @@ describe("TypeScriptLoader", () => { expect(() => loader(filePath, readFixtureContent(filePath))).toThrowError(); }); + it("should use the same instance of ts-node across multiple calls", () => { + const filePath = path.resolve(fixturesPath, "valid.fixture.ts"); + loader(filePath, readFixtureContent(filePath)); + loader(filePath, readFixtureContent(filePath)); + loader(filePath, readFixtureContent(filePath)); + expect(tsNodeSpy).toHaveBeenCalledTimes(1); + }); + it("should throw a TypeScriptCompileError on error", () => { try { const filePath = path.resolve(fixturesPath, "invalid.fixture.ts"); diff --git a/lib/loader.ts b/lib/loader.ts index 2a93020..2fdba2f 100644 --- a/lib/loader.ts +++ b/lib/loader.ts @@ -3,14 +3,14 @@ import { register, RegisterOptions } from "ts-node"; import { TypeScriptCompileError } from "./typescript-compile-error"; export function TypeScriptLoader(options?: RegisterOptions): Loader { - const tsNodeInstance = register({ ...options, compilerOptions: { module: "commonjs" } }) + const tsNodeInstance = register({ + ...options, + compilerOptions: { module: "commonjs" }, + }); return (path: string, content: string) => { try { // cosmiconfig requires the transpiled configuration to be CJS - tsNodeInstance.compile( - content, - path - ); + tsNodeInstance.compile(content, path); const result = require(path); // `default` is used when exporting using export default, some modules