forked from import-js/eslint-import-resolver-typescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (77 loc) · 2.17 KB
/
index.js
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
'use strict';
const path = require('path');
const resolve = require('resolve');
const tsconfigPaths = require('tsconfig-paths');
const debug = require('debug');
const log = debug('eslint-import-resolver-typescript');
/**
* @param {string} source the module to resolve; i.e './some-module'
* @param {string} file the importing file's full path; i.e. '/usr/local/bin/file.js'
*/
function resolveFile(source, file, config) {
log('looking for:', source);
// don't worry about core node modules
if (resolve.isCore(source)) {
log('matched core:', source);
return {
found: true,
path: null,
};
}
let foundTsPath = null;
const extensions = Object.keys(require.extensions).concat(
'.ts',
'.tsx',
'.d.ts',
);
// setup tsconfig-paths
const searchStart = config.directory || process.cwd();
const configLoaderResult = tsconfigPaths.loadConfig(searchStart);
if (configLoaderResult.resultType === 'success') {
const matchPath = tsconfigPaths.createMatchPath(
configLoaderResult.absoluteBaseUrl,
configLoaderResult.paths,
);
// look for files based on setup tsconfig "paths"
foundTsPath = matchPath(source, undefined, undefined, extensions);
if (foundTsPath) {
log('matched ts path:', foundTsPath);
}
} else {
log('failed to init tsconfig-paths:', configLoaderResult.message);
// this can happen if the user has problems with their tsconfig
// or if it's valid, but they don't have baseUrl set
}
// note that even if we match via tsconfig-paths, we still need to do a final resolve
let foundNodePath;
try {
foundNodePath = resolve.sync(foundTsPath || source, {
extensions,
basedir: path.dirname(path.resolve(file)),
packageFilter,
});
} catch (err) {
foundNodePath = null;
}
if (foundNodePath) {
log('matched node path:', foundNodePath);
return {
found: true,
path: foundNodePath,
};
}
log('didnt find', source);
return {
found: false,
};
}
function packageFilter(pkg) {
if (pkg['jsnext:main']) {
pkg['main'] = pkg['jsnext:main'];
}
return pkg;
}
module.exports = {
interfaceVersion: 2,
resolve: resolveFile,
};