This repository was archived by the owner on Nov 19, 2020. It is now read-only.
forked from simonhaenisch/rollup-plugin-typescript-paths
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
99 lines (75 loc) · 2.31 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { join } from 'path';
import { CompilerOptions, findConfigFile, nodeModuleNameResolver, sys } from 'typescript';
import { Plugin } from 'rollup';
export const typescriptPaths = ({
tsConfigPath = findConfigFile('./', sys.fileExists, 'tsconfig.lib.json'),
absolute = true,
transform,
}: Options = {}): Plugin => {
const { compilerOptions, outDir } = getTsConfig(tsConfigPath);
return {
name: 'resolve-typescript-paths',
resolveId: (importee: string, importer?: string) => {
if (typeof importer === 'undefined' || importee.startsWith('\0') || !compilerOptions.paths) {
return null;
}
const hasMatchingPath = Object.keys(compilerOptions.paths).some(path =>
new RegExp(path.replace('*', '\\w*')).test(importee),
);
if (!hasMatchingPath) {
return null;
}
const { resolvedModule } = nodeModuleNameResolver(importee, importer, compilerOptions, sys);
if (!resolvedModule) {
return null;
}
const { resolvedFileName } = resolvedModule;
if (!resolvedFileName || resolvedFileName.endsWith('.d.ts')) {
return null;
}
const jsFileName = join(outDir, resolvedFileName.replace(/\.tsx?$/i, '.js'));
let resolved = absolute ? sys.resolvePath(jsFileName) : jsFileName;
if (transform) {
resolved = transform(resolved);
}
return resolved;
},
};
};
const getTsConfig = (configPath?: string): TsConfig => {
const defaults: TsConfig = { compilerOptions: {}, outDir: '.' };
if (!configPath) {
return defaults;
}
const configJson = sys.readFile(configPath);
if (!configJson) {
return defaults;
}
const config: Partial<TsConfig> = JSON.parse(configJson);
return { ...defaults, ...config };
};
export interface Options {
/**
* Custom path to your `tsconfig.json`. Use this if the plugin can't seem to
* find the correct one by itself.
*/
tsConfigPath?: string;
/**
* Whether to resolve to absolute paths or not; defaults to `true`.
*/
absolute?: boolean;
/**
* If the plugin successfully resolves a path, this function allows you to
* hook into the process and transform that path before it is returned.
*/
transform?(path: string): string;
}
interface TsConfig {
compilerOptions: CompilerOptions;
outDir: string;
}
/**
* For backwards compatibility.
*/
export const resolveTypescriptPaths = typescriptPaths;
export default typescriptPaths;