Skip to content

Commit

Permalink
Support shared config that forbids require() (prettier#15233)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored and medikoo committed Feb 15, 2024
1 parent 2e3b570 commit 914e7de
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 4 deletions.
9 changes: 9 additions & 0 deletions changelog_unreleased/api/15233.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#### Support shared config that forbids `require()` (#15233 by @fisker)

If an external shared config package is used, and the package `exports` don't have `require` or `default` export.

In Prettier stable Prettier fails when attempt to `require()` the package, and throws an error.

```text
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in <packageName>/package.json
```
10 changes: 6 additions & 4 deletions src/config/load-external-config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import requireFromFile from "../utils/require-from-file.js";
import importFromFile from "../utils/import-from-file.js";

const requireErrorCodesShouldBeIgnored = new Set([
"MODULE_NOT_FOUND",
"ERR_REQUIRE_ESM",
"ERR_PACKAGE_PATH_NOT_EXPORTED",
]);
async function loadExternalConfig(config, filepath) {
/*
Try `require()` first, this is how it works in Prettier v2.
Expand All @@ -12,10 +17,7 @@ async function loadExternalConfig(config, filepath) {
try {
return requireFromFile(config, filepath);
} catch (/** @type {any} */ error) {
if (
error?.code !== "MODULE_NOT_FOUND" &&
error?.code !== "ERR_REQUIRE_ESM"
) {
if (!requireErrorCodesShouldBeIgnored.has(error?.code)) {
throw error;
}
}
Expand Down
12 changes: 12 additions & 0 deletions tests/integration/__tests__/config-resolution.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,15 @@ test(".json5 config file(invalid)", async () => {
const error = /JSON5: invalid end of input at 2:1/;
await expect(prettier.resolveConfig(file)).rejects.toThrow(error);
});

test("support external module with `module` only `exports`", async () => {
const directory = path.join(
__dirname,
"../cli/config/external-config/esm-package-forbids-require",
);
const file = path.join(directory, "index.js");

await expect(prettier.resolveConfig(file)).resolves.toMatchObject({
printWidth: 79,
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("should have no semi");

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"prettier": "prettier-config-forbids-require"
}

0 comments on commit 914e7de

Please sign in to comment.