Skip to content

Commit bf2e0df

Browse files
feat: suggest the closest file name when a module is not found (#21727)
When resolving fails and no other hint applies, look at the request's directory and name the entry it comes closest to. A name that only differs in casing gets an explicit note, since such a build succeeds on a case-insensitive filesystem and fails on a case-sensitive one.
1 parent 8be212b commit bf2e0df

16 files changed

Lines changed: 245 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Suggest the closest file name, or a casing fix, when a module is not found.

‎lib/NormalModuleFactory.js‎

Lines changed: 140 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ const UseEffectRulePlugin = require("./rules/UseEffectRulePlugin");
3030
const LazySet = require("./util/LazySet");
3131
const { getScheme } = require("./util/URLAbsoluteSpecifier");
3232
const { cachedCleverMerge, cachedSetProperty } = require("./util/cleverMerge");
33-
const { join } = require("./util/fs");
33+
const { dirname, join, relative } = require("./util/fs");
3434
const {
35+
ABSOLUTE_PATH_REGEXP,
3536
escapeHashInPathRequest,
3637
parseResource,
3738
parseResourceWithoutFragment
@@ -162,6 +163,100 @@ const EMPTY_ELEMENTS = [];
162163

163164
const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/;
164165
const LEADING_DOT_EXTENSION_REGEX = /^[^.]/;
166+
// Nothing in `util/identifier` matches a request (as opposed to a path) shape.
167+
const RELATIVE_REQUEST_REGEXP = /^\.\.?[\\/]/;
168+
169+
/**
170+
* Computes the edit distance of two strings, counting swapped neighbors as one
171+
* edit and giving up as soon as the distance exceeds `max`.
172+
* @param {string} a first string
173+
* @param {string} b second string
174+
* @param {number} max largest distance worth distinguishing
175+
* @returns {number} the distance, or a value greater than `max` when it exceeds `max`
176+
*/
177+
const editDistance = (a, b, max) => {
178+
if (a === b) return 0;
179+
if (Math.abs(a.length - b.length) > max) return max + 1;
180+
/** @type {number[] | undefined} */
181+
let rowBeforePrevious;
182+
/** @type {number[]} */
183+
let previousRow = [];
184+
for (let column = 0; column <= b.length; column++) previousRow.push(column);
185+
for (let row = 1; row <= a.length; row++) {
186+
const currentRow = [row];
187+
let rowMinimum = row;
188+
for (let column = 1; column <= b.length; column++) {
189+
let distance = Math.min(
190+
previousRow[column - 1] + (a[row - 1] === b[column - 1] ? 0 : 1),
191+
previousRow[column] + 1,
192+
currentRow[column - 1] + 1
193+
);
194+
if (
195+
rowBeforePrevious &&
196+
a[row - 1] === b[column - 2] &&
197+
a[row - 2] === b[column - 1]
198+
) {
199+
distance = Math.min(distance, rowBeforePrevious[column - 2] + 1);
200+
}
201+
currentRow.push(distance);
202+
if (distance < rowMinimum) rowMinimum = distance;
203+
}
204+
if (rowMinimum > max) return max + 1;
205+
rowBeforePrevious = previousRow;
206+
previousRow = currentRow;
207+
}
208+
return previousRow[b.length];
209+
};
210+
211+
/**
212+
* Names an entry of a directory can be requested by: as written, and without
213+
* the extension the resolver would have appended.
214+
* @param {string} entry name of a directory entry
215+
* @param {Set<string>} extensions the resolvable extensions
216+
* @returns {string[]} names the entry answers to
217+
*/
218+
const namesForEntry = (entry, extensions) => {
219+
const names = [entry];
220+
for (const extension of extensions) {
221+
if (entry.length > extension.length && entry.endsWith(extension)) {
222+
names.push(entry.slice(0, -extension.length));
223+
}
224+
}
225+
return names;
226+
};
227+
228+
/**
229+
* Picks the entry of a directory a failed request most likely meant. Ties are
230+
* broken by name so the hint does not depend on the order the directory lists.
231+
* @param {string} requested the requested file name
232+
* @param {string[]} entries names in the directory
233+
* @param {Set<string>} extensions the resolvable extensions
234+
* @returns {{ entry: string, distance: number } | undefined} the closest entry and how far it is from the request
235+
*/
236+
const findClosestEntry = (requested, entries, extensions) => {
237+
// A typo is only distinguishable from an unrelated name once the name is
238+
// long enough, so short requests are matched by casing alone.
239+
let allowedDistance = requested.length < 4 ? 0 : requested.length < 8 ? 1 : 2;
240+
const lowerCaseRequested = requested.toLowerCase();
241+
/** @type {{ entry: string, distance: number } | undefined} */
242+
let best;
243+
for (const entry of entries) {
244+
// The entry exists as requested, so the request failed for another reason.
245+
if (entry === requested) return;
246+
for (const name of namesForEntry(entry, extensions)) {
247+
const distance = editDistance(
248+
lowerCaseRequested,
249+
name.toLowerCase(),
250+
allowedDistance
251+
);
252+
if (distance > allowedDistance) continue;
253+
if (best && distance === allowedDistance && entry >= best.entry) continue;
254+
allowedDistance = distance;
255+
best = { entry, distance };
256+
}
257+
}
258+
return best;
259+
};
165260

166261
/**
167262
* Replays the file/context/missing dependencies captured by a loader resolve
@@ -1267,6 +1362,45 @@ ${hints.join("\n\n")}`;
12671362
resolveContext,
12681363
callback
12691364
) {
1365+
/**
1366+
* Names the entry of the request's directory it comes closest to, for
1367+
* requests that failed over a typo or the casing of a file name.
1368+
* @param {(hint?: string) => void} callback callback
1369+
* @returns {void}
1370+
*/
1371+
const suggestClosestEntry = (callback) => {
1372+
const { path: requestPath } = parseResource(unresolvedResource);
1373+
const isAbsolute = ABSOLUTE_PATH_REGEXP.test(requestPath);
1374+
if (!isAbsolute && !RELATIVE_REQUEST_REGEXP.test(requestPath)) {
1375+
return callback();
1376+
}
1377+
const absoluteRequest = isAbsolute
1378+
? requestPath
1379+
: join(this.fs, context, requestPath);
1380+
const directory = dirname(this.fs, absoluteRequest);
1381+
const requestedName = relative(this.fs, directory, absoluteRequest);
1382+
// A request ending in '.' or '..' names a directory, not an entry in one.
1383+
if (!requestPath.endsWith(requestedName)) return callback();
1384+
this.fs.readdir(directory, (err, entries) => {
1385+
if (err || !entries) return callback();
1386+
const closest = findClosestEntry(
1387+
requestedName,
1388+
/** @type {string[]} */ (entries),
1389+
resolver.options.extensions
1390+
);
1391+
if (!closest) return callback();
1392+
const suggestion =
1393+
requestPath.slice(0, -requestedName.length) + closest.entry;
1394+
callback(
1395+
closest.distance === 0
1396+
? `Did you mean '${suggestion}'?
1397+
'${closest.entry}' exists in that directory and differs from the request only in casing. Case-sensitive filesystems (most Linux ones) fail to resolve it, even when the same build succeeds on a case-insensitive one.`
1398+
: `Did you mean '${suggestion}'?
1399+
'${closest.entry}' is the closest name in that directory. It differs from the request by ${closest.distance === 1 ? "1 character" : `${closest.distance} characters`}, ignoring case and file extension.`
1400+
);
1401+
});
1402+
};
1403+
12701404
asyncLib.parallel(
12711405
[
12721406
(callback) => {
@@ -1368,7 +1502,11 @@ If changing the source code is not an option there is also a resolve options cal
13681502
],
13691503
(err, hints) => {
13701504
if (err) return callback(err);
1371-
callback(null, /** @type {string[]} */ (hints).filter(Boolean));
1505+
const resolveHints = /** @type {string[]} */ (hints).filter(Boolean);
1506+
// The hints above explain why an existing file was rejected and name it
1507+
// themselves, so only look for a similar name when none of them applied.
1508+
if (resolveHints.length > 0) return callback(null, resolveHints);
1509+
suggestClosestEntry((hint) => callback(null, hint ? [hint] : []));
13721510
}
13731511
);
13741512
}

‎test/Errors.test.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ describe("Errors", () => {
321321
"errors": Array [
322322
Object {
323323
"loc": "2:0-17",
324-
"message": "Module not found: Error: Can't resolve './FILE' in '<cwd>/test/fixtures/errors'",
324+
"message": "Module not found: Error: Can't resolve './FILE' in '<cwd>/test/fixtures/errors'\\nDid you mean './file.js'?\\n'file.js' exists in that directory and differs from the request only in casing. Case-sensitive filesystems (most Linux ones) fail to resolve it, even when the same build succeeds on a case-insensitive one.",
325325
"moduleId": "./case-sensitive.js",
326326
"moduleIdentifier": "<cwd>/test/fixtures/errors/case-sensitive.js",
327327
"moduleName": "./case-sensitive.js",
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"use strict";
2+
3+
module.exports = 42;
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"use strict";
2+
3+
module.exports = [
4+
[
5+
/Can't resolve '\.\/button\.js'/,
6+
/Did you mean '\.\/Button\.js'\?/,
7+
/'Button\.js' exists in that directory and differs from the request only in casing/
8+
],
9+
[
10+
/Can't resolve '\.\/button'/,
11+
/Did you mean '\.\/Button\.js'\?/,
12+
/'Button\.js' exists in that directory and differs from the request only in casing/
13+
]
14+
];
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
var never = false;
2+
3+
it("should point at the file a request only differs in casing from", function () {
4+
if (never) {
5+
require("./button.js");
6+
require("./button");
7+
}
8+
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"use strict";
2+
3+
const fs = require("fs");
4+
const path = require("path");
5+
6+
// A case-only mismatch resolves fine on a case-insensitive filesystem,
7+
// so there is no failing request to hint about there.
8+
module.exports = () => !fs.existsSync(path.resolve(__dirname, "BUTTON.js"));
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {};
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"use strict";
2+
3+
module.exports = 42;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`errors 1`] = `
4+
Array [
5+
"Module not found: Error: Can't resolve './Componet.js' in '<TEST_DIR>'
6+
Did you mean './Component.js'?
7+
'Component.js' is the closest name in that directory. It differs from the request by 1 character, ignoring case and file extension.",
8+
"Module not found: Error: Can't resolve './Componet' in '<TEST_DIR>'
9+
Did you mean './Component.js'?
10+
'Component.js' is the closest name in that directory. It differs from the request by 1 character, ignoring case and file extension.",
11+
"Module not found: Error: Can't resolve './utlis' in '<TEST_DIR>'
12+
Did you mean './utils.js'?
13+
'utils.js' is the closest name in that directory. It differs from the request by 1 character, ignoring case and file extension.",
14+
"Module not found: Error: Can't resolve './tranlsatoins.js' in '<TEST_DIR>'
15+
Did you mean './translations.js'?
16+
'translations.js' is the closest name in that directory. It differs from the request by 2 characters, ignoring case and file extension.",
17+
"Module not found: Error: Can't resolve './bundel' in '<TEST_DIR>'
18+
Did you mean './bundle.min.js'?
19+
'bundle.min.js' is the closest name in that directory. It differs from the request by 1 character, ignoring case and file extension.",
20+
"Module not found: Error: Can't resolve './nothing-like-this-here.js' in '<TEST_DIR>'",
21+
"Module not found: Error: Can't resolve './no-such-directory/Componet.js' in '<TEST_DIR>'",
22+
"Module not found: Error: Can't resolve './directory-without-index' in '<TEST_DIR>'",
23+
"Module not found: Error: Can't resolve '/definitely-not-a-file-in-the-filesystem-root.js' in '<TEST_DIR>'",
24+
]
25+
`;

0 commit comments

Comments
 (0)