Skip to content

Commit 1febd9f

Browse files
refactor: code update
1 parent cd39fe6 commit 1febd9f

1 file changed

Lines changed: 33 additions & 8 deletions

File tree

packages/webpack-cli/src/webpack-cli.ts

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
program,
1515
} from "commander";
1616
import { type Config as EnvinfoConfig, type Options as EnvinfoOptions } from "envinfo";
17+
import { distance } from "fastest-levenshtein";
1718
import { type prepare } from "rechoir";
1819
import {
1920
type Argument as WebpackArgument,
@@ -1942,17 +1943,43 @@ class WebpackCLI {
19421943
return;
19431944
}
19441945

1945-
const isInfo = ["commander.helpDisplayed", "commander.version"].includes(error.code);
1946+
if (error.code === "commander.unknownOption") {
1947+
let name = error.message.match(/'(.+)'/) as string | null;
19461948

1947-
if (isInfo) {
1948-
process.exit(0);
1949-
return;
1949+
if (name) {
1950+
name = name[1].slice(2);
1951+
1952+
if (name.includes("=")) {
1953+
[name] = name.split("=");
1954+
}
1955+
1956+
const { operands } = this.program.parseOptions(this.program.args);
1957+
const operand =
1958+
typeof operands[0] !== "undefined" ? operands[0] : WebpackCLI.#commands.build.rawName;
1959+
1960+
if (operand) {
1961+
const command = this.#findCommandByName(operand);
1962+
1963+
if (!command) {
1964+
this.logger.error(`Can't find and load command '${operand}'`);
1965+
this.logger.error("Run 'webpack --help' to see available commands and options");
1966+
process.exit(2);
1967+
}
1968+
1969+
for (const option of command.options) {
1970+
if (
1971+
!(option as Option & { internal?: boolean }).internal &&
1972+
distance(name, option.long?.slice(2) as string) < 3
1973+
) {
1974+
this.logger.error(`Did you mean '--${option.name()}'?`);
1975+
}
1976+
}
1977+
}
1978+
}
19501979
}
19511980

19521981
this.logger.error("Run 'webpack --help' to see available commands and options");
19531982
process.exit(2);
1954-
1955-
throw error;
19561983
});
19571984

19581985
this.program.option("--color", "Enable colors on console.");
@@ -2079,8 +2106,6 @@ class WebpackCLI {
20792106
} else {
20802107
this.logger.error(`Unknown command or entry '${operand}'`);
20812108

2082-
const { distance } = await import("fastest-levenshtein");
2083-
20842109
const found = Object.values(WebpackCLI.#commands).find(
20852110
(commandOptions) => distance(operand, commandOptions.rawName) < 3,
20862111
);

0 commit comments

Comments
 (0)