Skip to content

Commit

Permalink
Merge pull request #5933 from NomicFoundation/improve-types-modules-e…
Browse files Browse the repository at this point in the history
…rror

Improve how we detect if the project is CJS
  • Loading branch information
alcuadrado authored Nov 6, 2024
2 parents f9f8cc2 + 9f246cd commit ae4c8b1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 21 deletions.
21 changes: 0 additions & 21 deletions v-next/hardhat/src/internal/cli/error-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,6 @@ export function printErrorMessages(
shouldShowStackTraces: boolean = false,
print: (message: string) => void = console.error,
): void {
// If Hardhat is running on CJS mode we print a special message
if (isRequireESMError(error)) {
printEsmOnlyErrorMessage(print);
return;
}

const showStackTraces =
shouldShowStackTraces ||
getErrorWithCategory(error).category === ErrorCategory.OTHER;
Expand Down Expand Up @@ -157,18 +151,3 @@ function getErrorMessages(error: unknown): ErrorMessages {
};
}
}

function isRequireESMError(error: unknown): boolean {
return (
error instanceof Error &&
"code" in error &&
error.code === "ERR_REQUIRE_CYCLE_MODULE" &&
error.message.includes("Cannot require() ES Module")
);
}

function printEsmOnlyErrorMessage(print: (message: string) => void) {
print(`Hardhat only supports ESM projects.
Please make sure you have \`"type": "module"\` in your package.json`);
}
32 changes: 32 additions & 0 deletions v-next/hardhat/src/internal/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
assertHardhatInvariant,
} from "@ignored/hardhat-vnext-errors";
import { isCi } from "@ignored/hardhat-vnext-utils/ci";
import { readClosestPackageJson } from "@ignored/hardhat-vnext-utils/package";
import { kebabToCamelCase } from "@ignored/hardhat-vnext-utils/string";
import debug from "debug";
import { register } from "tsx/esm/api";
Expand Down Expand Up @@ -87,6 +88,16 @@ export async function main(

const projectRoot = await resolveProjectRoot(configPath);

const esmErrorPrinted = await printEsmErrorMessageIfNecessary(
projectRoot,
print,
);

if (esmErrorPrinted) {
process.exitCode = 1;
return;
}

if (options.registerTsx) {
register();
}
Expand Down Expand Up @@ -560,3 +571,24 @@ function validateRequiredArguments(
{ argument: missingRequiredArgument.name },
);
}

/**
* Prints an error message if the user is running Hardhat on CJS mode, returning
* `true` if the message was printed.
*/
async function printEsmErrorMessageIfNecessary(
projectRoot: string,
print: (message: string) => void,
): Promise<boolean> {
const packageJson = await readClosestPackageJson(projectRoot);

if (packageJson.type !== "module") {
print(`Hardhat only supports ESM projects.
Please make sure you have \`"type": "module"\` in your package.json`);

return true;
}

return false;
}

0 comments on commit ae4c8b1

Please sign in to comment.