Support shared config that forbids require() (#15233)
This commit is contained in:
1 parent
1ce97d13a3
commit
a35008fb0a
7 files changed
+41
-4
No files matched your search
@@ -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
|
||||
```
|
||||
@@ -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.
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
console.log("should have no semi");
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export default { printWidth: 79 }
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "prettier-config-forbids-require",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"import": "./index.js"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"prettier": "prettier-config-forbids-require"
|
||||
}
|
||||
Reference in new issue
Block a user