|
| 1 | +import { join } from 'path'; |
1 | 2 | import { CompilerOptions, findConfigFile, nodeModuleNameResolver, sys } from 'typescript'; |
2 | 3 |
|
3 | | -export const resolveTypescriptPaths = (options: Options = {}) => { |
4 | | - const compilerOptions = getCompilerOptions(options.tsConfigPath); |
| 4 | +export const resolveTypescriptPaths = ({ |
| 5 | + tsConfigPath = findConfigFile('./', sys.fileExists), |
| 6 | + absolute = true, |
| 7 | +}: Options = {}) => { |
| 8 | + const { compilerOptions, outDir } = getTsConfig(tsConfigPath); |
5 | 9 |
|
6 | 10 | return { |
7 | 11 | name: 'resolve-typescript-paths', |
@@ -30,31 +34,45 @@ export const resolveTypescriptPaths = (options: Options = {}) => { |
30 | 34 | return null; |
31 | 35 | } |
32 | 36 |
|
33 | | - return resolvedFileName; |
| 37 | + const jsFileName = join(outDir, resolvedFileName.replace(/\.tsx?$/i, '.js')); |
| 38 | + |
| 39 | + return absolute ? sys.resolvePath(jsFileName) : jsFileName; |
34 | 40 | }, |
35 | 41 | }; |
36 | 42 | }; |
37 | 43 |
|
38 | | -const getCompilerOptions = (configPath = findConfigFile('./', sys.fileExists)): CompilerOptions => { |
| 44 | +const getTsConfig = (configPath?: string): TsConfig => { |
| 45 | + const defaults: TsConfig = { compilerOptions: {}, outDir: '.' }; |
| 46 | + |
39 | 47 | if (!configPath) { |
40 | | - return {}; |
| 48 | + return defaults; |
41 | 49 | } |
42 | 50 |
|
43 | 51 | const configJson = sys.readFile(configPath); |
44 | 52 |
|
45 | 53 | if (!configJson) { |
46 | | - return {}; |
| 54 | + return defaults; |
47 | 55 | } |
48 | 56 |
|
49 | | - const config: { compilerOptions?: CompilerOptions } = JSON.parse(configJson); |
50 | | - |
51 | | - if (!config || !config.compilerOptions) { |
52 | | - return {}; |
53 | | - } |
| 57 | + const config: Partial<TsConfig> = JSON.parse(configJson); |
54 | 58 |
|
55 | | - return config.compilerOptions; |
| 59 | + return { ...defaults, ...config }; |
56 | 60 | }; |
57 | 61 |
|
58 | 62 | export interface Options { |
| 63 | + /** |
| 64 | + * Custom path to your `tsconfig.json`. Use this if the plugin can't seem to |
| 65 | + * find the correct one by itself. |
| 66 | + */ |
59 | 67 | tsConfigPath?: string; |
| 68 | + |
| 69 | + /** |
| 70 | + * Whether to resolve to absolute paths or not; defaults to `true`. |
| 71 | + */ |
| 72 | + absolute?: boolean; |
| 73 | +} |
| 74 | + |
| 75 | +interface TsConfig { |
| 76 | + compilerOptions: CompilerOptions; |
| 77 | + outDir: string; |
60 | 78 | } |
0 commit comments