Support read config from package.json with JSONC syntax on Bun (#17041)
This commit is contained in:
1 parent
1026afd4b4
commit
c13bfc75fb
2 files changed
+50
-8
No files matched your search
@@ -0,0 +1,22 @@
|
||||
#### Support read config from `package.json` with JSONC syntax on Bun (#17041 by @fisker)
|
||||
|
||||
[Bun 1.2 added JSONC support in `package.json`](https://bun.sh/blog/bun-v1.2#jsonc-support-in-package-json), in previous version of Prettier, it will ignore `prettier` config in it. Since Prettier main, we can read `prettier` config from it without error.
|
||||
|
||||
However, since it's just a Bun feature and not supported by Node.js, it can only work when running Prettier with Bun.
|
||||
|
||||
Important note: Prettier uses [`json-stringify` parser](https://prettier.io/docs/en/options#parser) to format `package.json` file by default, to support formatting `package.json` file with JSONC syntax, you need override the parser option
|
||||
|
||||
```js
|
||||
export default {
|
||||
overrides: [
|
||||
{
|
||||
files: ["package.json"],
|
||||
options: {
|
||||
parser: "jsonc",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
If you can't upgrade Prettier for some reason, you can still use JSONC syntax in `package.json`, but don't put your `prettier` config in it, you'll have to use another [configuration file](https://prettier.io/docs/en/configuration).
|
||||
@@ -15,13 +15,33 @@ async function readJson(file) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadJs(file) {
|
||||
async function importModuleDefault(file) {
|
||||
const module = await import(pathToFileURL(file).href);
|
||||
return module.default;
|
||||
}
|
||||
|
||||
async function readPackageJson(file) {
|
||||
try {
|
||||
return await readJson(file);
|
||||
} catch (error) {
|
||||
// TODO: Add tests for this
|
||||
// Bun supports comments and trialing comma in `package.json`
|
||||
// And it can load via `import()`
|
||||
// https://bun.sh/blog/bun-v1.2#jsonc-support-in-package-json
|
||||
if (process.versions.bun) {
|
||||
try {
|
||||
return await importModuleDefault(file);
|
||||
} catch {
|
||||
// No op
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigFromPackageJson(file) {
|
||||
const { prettier } = await readJson(file);
|
||||
const { prettier } = await readPackageJson(file);
|
||||
return prettier;
|
||||
}
|
||||
|
||||
@@ -60,12 +80,12 @@ const loaders = {
|
||||
}
|
||||
},
|
||||
".json": readJson,
|
||||
".js": loadJs,
|
||||
".mjs": loadJs,
|
||||
".cjs": loadJs,
|
||||
".ts": loadJs,
|
||||
".mts": loadJs,
|
||||
".cts": loadJs,
|
||||
".js": importModuleDefault,
|
||||
".mjs": importModuleDefault,
|
||||
".cjs": importModuleDefault,
|
||||
".ts": importModuleDefault,
|
||||
".mts": importModuleDefault,
|
||||
".cts": importModuleDefault,
|
||||
".yaml": loadYaml,
|
||||
".yml": loadYaml,
|
||||
// No extension
|
||||
|
||||
Reference in new issue
Block a user