UNPKG

ts-jest-resolver

Version:

A resolver for `jest` that uses same strategy as TS when resolving files with JavaScript extension (".js").

1 lines 3.27 kB
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import type { ResolverOptions } from 'jest-resolve';\n\nexport type Path = string;\n\nexport type { ResolverOptions };\n\ntype Resolution = {\n /**\n * A `RegExp` that checks if file name has a JavaScript extension.\n */\n matcher: RegExp;\n\n /**\n * A list of TypeScript file extensions, in the order used by its resolver.\n */\n extensions: string[];\n};\n\nconst resolutions: Resolution[] = [\n {\n matcher: /\\.js$/i,\n extensions: ['.ts', '.tsx'],\n },\n {\n matcher: /\\.jsx$/i,\n extensions: ['.ts', '.tsx', '.js'],\n },\n {\n matcher: /\\.cjs$/i,\n extensions: ['.cts'],\n },\n {\n matcher: /\\.mjs$/i,\n extensions: ['.mts'],\n },\n];\n\n/**\n * A resolver for `jest` that uses same strategy as TS when resolving files with\n * JavaScript extension (\".js\"). Otherwise it just uses default resolver.\n *\n * When receives a path with JavaScript extension (\".js\" or \".jsx\"):\n * 1. It tries to resolve to a path with \".tsx\".\n * 2. If no file was found, it tries to resolve to a path with \".ts\".\n * 3. If no file was found, it resolves to original path (with \".js\" or \".jsx\").\n *\n * When receives a path with ES modules extension (\".mjs\"):\n * 1. It tries to resolve to a path with \".mts\".\n * 2. If no file was found, it resolves to original path (with \".mjs\").\n *\n * When receives a path with CommonJS modules extension (\".cjs\"):\n * 1. It tries to resolve to a path with \".cts\".\n * 2. If no file was found, it resolves to original path (with \".cjs\").\n */\nfunction resolverForTSJest(path: Path, options: ResolverOptions): Path {\n const resolver = options.defaultResolver;\n\n const resolution = resolutions.find(({ matcher }) => matcher.test(path));\n\n if (resolution) {\n for (const extension of resolution.extensions) {\n try {\n return resolver(path.replace(resolution.matcher, extension), options);\n } catch {\n continue;\n }\n }\n }\n\n return resolver(path, options);\n}\n\nexport default resolverForTSJest;\n"],"names":[],"mappings":";;;;;;;;AAkBA,IAAM,WAAW,GAAiB;AAChC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