jscheid / prettier.el

Prettier code formatting for Emacs.
GNU General Public License v3.0
163 stars 11 forks source link

How to tell `prettier` to use json parser instead of default javascript parser for package.json? #101

Closed jangid closed 2 years ago

jangid commented 2 years ago

This is more a question than bug-report. I couldn't find any forum link so posting it here. Others might as well find this useful.

I could not find a configuration in Info manual for setting prettier to use JSON parser for package.json file. By default it is using some javascript parser which is producing error. Please add this section to manual. Also please add an answer here. Thanks.

laampui commented 2 years ago

C-u M-x prettier-prettify ?

jscheid commented 2 years ago

I'll find some time to look at this soon. @jangid it sounds like a bug, it should use the correct parser by default. There's been commits to that effect before, but maybe something has changed in latest Prettier.

jscheid commented 2 years ago

@jangid I've just had a look -- this seems to be working for me. What output do you get when you switch to some package.json buffer and do M-: (prettier--parsers) RET? Should be (json-stringify json).

If that's not what you're getting, can you check that these parsers are enabled in your customization? (M-x customize-option prettier-enabled-parsers RET) and that you're using the latest version of this package?

jangid commented 2 years ago

The output of M-: (prettier--parsers) RET is (babel meriyah espree flow babel-flow). But when I check the value of variable prettier-enabled-parsers it shows (angular babel babel-flow babel-ts css elm espree flow graphql html java json json5 json-stringify less lua markdown mdx meriyah php postgresql pug python ruby scss sh solidity svelte swift toml typescript vue xml yaml). As you can see (json-stringify json) are part of it.

But i still get this error

/home/pankaj/work/moodraa/moodraa-next/package.json: SyntaxError: Unexpected token (2:12)
  1 | {
> 2 |   "private": true,
    |            ^

This works fine with CLI prettier. and the prettier-js package which spawns new process.

jscheid commented 2 years ago

Ah, I think I know what it is. You're using js-mode for your package.json. Use json-mode and it should work.

I know this isn't ideal, really it should be using the same parser that Prettier CLI uses regardless of mode. I'm planning to change that. Hope you can work around it for now using json-mode.

jangid commented 2 years ago

Yes. This worked. I'll use this workaround till this is fixed. Thanks a lot for investigating this and for the nice package.

rofrol commented 1 year ago

Just installing https://github.com/joshwnj/json-mode solved the problem.

Not sure if this will be needed (add-to-list 'auto-mode-alist '("\\.json\\'" . json-mode)) in some case.