-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpatchModuleResolver.js
87 lines (76 loc) · 2.51 KB
/
patchModuleResolver.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
/*
* This files transform's ESLint's module resolver to be able to load plugins from other locations
* The current version is only able to load dependencies relative to the current working directory.
* Which in the case of global installations, GitHub Hooks or similar doesn't work.
*
* Solution inspired by https://github.com/microsoft/rushstack/tree/master/stack/eslint-patch
*
* This hack should be removed as soon as solutions are found in :
* - https://github.com/eslint/eslint/issues/3458
* - https://github.com/eslint/rfcs/pull/9
*/
const path = require("path");
const fs = require("fs");
function getESLintrcFolderFromModule() {
let currentModule = module;
while (
!/@eslint[\\/]eslintrc[\\/]lib[\\/]config-array-factory.js/i.test(
currentModule.filename
)
) {
if (!currentModule.parent) {
// This was tested with ESLint 7.5.0; other versions may not work
throw new Error(
"Failed to patch ESLint because the calling module was not recognized"
);
}
currentModule = currentModule.parent;
}
return path.join(path.dirname(currentModule.filename), "..");
}
function patch(eslintPath) {
const moduleResolverPath = path.join(eslintPath, "dist/eslintrc.cjs");
const ModuleResolver = require(moduleResolverPath).Legacy.ModuleResolver;
const originalResolve = ModuleResolver.resolve;
if (ModuleResolver.__patched) {
return;
}
ModuleResolver.__patched = true;
ModuleResolver.resolve = function(moduleName, relativeToPath) {
try {
// First check for the module relative to the current location
return originalResolve(moduleName, __filename);
} catch (e) {
// OR fallback to the default behaviour of ESLint
return originalResolve(moduleName, relativeToPath);
}
};
}
let succeeded = false;
const errors = [];
// Patch @eslint/eslintrc when it's found
const eslintrcPossiblePaths = [
getESLintrcFolderFromModule,
() =>
require
.resolve("@eslint/eslintrc/package.json")
.replace(/\/package\.json$/, ""),
() => path.join(process.cwd(), "node_modules", "@eslint", "eslintrc")
];
eslintrcPossiblePaths.forEach(mainEslintrcFolderFn => {
try {
const mainEslintrcFolder = mainEslintrcFolderFn();
if (fs.existsSync(mainEslintrcFolder)) {
patch(mainEslintrcFolder);
succeeded = true;
}
} catch (e) {
errors.push(e);
}
});
if (!succeeded) {
errors.forEach(error => console.error(error));
throw new Error(
"Impossible to patch ESLint for module resolution. All attempts failed."
);
}