Skip to content

Commit 37c4a00

Browse files
committed
feat: make ts-node an optional dependency
1 parent 62c8728 commit 37c4a00

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

lib/loader.ts

+16-2
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,34 @@ import type { Loader } from "cosmiconfig";
22
import type { RegisterOptions, Service } from "ts-node";
33

44
import { TypeScriptCompileError } from "./typescript-compile-error";
5+
import { instanceOfNodeError } from "./util";
56

67
export function TypeScriptLoader(options?: RegisterOptions): Loader {
78
let tsNodeInstance: Service;
89

910
return (path: string, content: string) => {
10-
try {
11-
if (!tsNodeInstance) {
11+
if (!tsNodeInstance) {
12+
try {
1213
const { register } = require("ts-node") as typeof import("ts-node");
1314
tsNodeInstance = register({
1415
...options,
1516
compilerOptions: { module: "commonjs" },
1617
});
18+
} catch (error) {
19+
if (
20+
instanceOfNodeError(error) &&
21+
error.code === "ERR_MODULE_NOT_FOUND"
22+
) {
23+
throw new Error(
24+
"cosmiconfig-typescript-loader: 'ts-node' is required for loading TypeScript cosmiconfig configuration files." +
25+
`Make sure it is installed\nError: ${error.message}`
26+
);
27+
}
28+
throw error;
1729
}
30+
}
1831

32+
try {
1933
// cosmiconfig requires the transpiled configuration to be CJS
2034
tsNodeInstance.compile(content, path);
2135
const result = require(path);

lib/util.ts

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export function instanceOfNodeError(
2+
error: unknown
3+
): error is NodeJS.ErrnoException {
4+
return (
5+
error instanceof Error &&
6+
// https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cddd0b7aab18761214d26a0c7012cf45de5285a9
7+
(error as Record<string, any>).code !== undefined
8+
);
9+
}

package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,11 @@
3636
"peerDependencies": {
3737
"@types/node": "*",
3838
"cosmiconfig": ">=7",
39-
"ts-node": ">=10",
4039
"typescript": ">=4"
4140
},
41+
"optionalDependencies": {
42+
"ts-node": ">=10"
43+
},
4244
"devDependencies": {
4345
"@swc/core": "^1.3.44",
4446
"@swc/jest": "^0.2.24",

0 commit comments

Comments
 (0)