generated from VitorLuizC/typescript-library-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
69 lines (59 loc) · 1.91 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import type defaultResolver from 'jest-resolve/build/defaultResolver';
type Resolution = {
/**
* A `RegExp` that checks if file name has a JavaScript extension.
*/
matcher: RegExp;
/**
* A list of TypeScript file extensions, in the order used by its resolver.
*/
extensions: string[];
};
const resolutions: Resolution[] = [
{
matcher: /\.jsx?$/i,
extensions: ['.tsx', '.ts'],
},
{
matcher: /\.mjs$/i,
extensions: ['.mts'],
},
{
matcher: /\.cjs$/i,
extensions: ['.cts'],
},
];
export type Path = Parameters<typeof defaultResolver>[0];
export type ResolverOptions = Parameters<typeof defaultResolver>[1];
/**
* A resolver for `jest` that uses same strategy as TS when resolving files with
* JavaScript extension (".js"). Otherwise it just uses default resolver.
*
* When receives a path with JavaScript extension (".js" or ".jsx"):
* 1. It tries to resolve to a path with ".tsx".
* 2. If no file was found, it tries to resolve to a path with ".ts".
* 3. If no file was found, it resolves to original path (with ".js" or ".jsx").
*
* When receives a path with ES modules extension (".mjs"):
* 1. It tries to resolve to a path with ".mts".
* 2. If no file was found, it resolves to original path (with ".mjs").
*
* When receives a path with CommonJS modules extension (".cjs"):
* 1. It tries to resolve to a path with ".cts".
* 2. If no file was found, it resolves to original path (with ".cjs").
*/
function resolverForTSJest(path: Path, options: ResolverOptions): Path {
const resolver = options.defaultResolver;
const resolution = resolutions.find(({ matcher }) => matcher.test(path));
if (resolution) {
for (const extension of resolution.extensions) {
try {
return resolver(path.replace(resolution.matcher, extension), options);
} catch {
continue;
}
}
}
return resolver(path, options);
}
export default resolverForTSJest;