Js-beautify: Add a setting for adding trailing/dangling commas

Created on 4 Sep 2016  路  8Comments  路  Source: beautify-web/js-beautify

Description

Historically, certain versions of Internet Explorer did not allow trailing commas in arrays or object literals,
or caused strange behaviour when they were present. These days, trailing commas are either removed by minification tools, or code is run in Internet Explorer 9 or later. As such, the advice for writing JavaScript code in many codebases has changed from removing trailing commas, to instead requiring them.

I would like to see an option, which would be off by default, for adding trailing commas to arrays and objects. (Possibly function argument lists and function calls with ES2017) Currently js-beautify will remove trailing commas, but this conflicts with the eslint configuration which is set up in my codebase, which means that js-beautify cannot be used on the code in my codebase without also applying eslint --fix, which isn't the fastest thing in the world.

Input

var x = [
    1,
    2,
    3,
];

var y = {
   a: 1,
   b: 2,
   b: 3,
];

var missing_comma = [
    1,
    2
]

Expected Output

I want js-beautify to leave my trailing commas alone, or add them.

var x = [
    1,
    2,
    3,
];

var y = {
   a: 1,
   b: 2,
   b: 3,
];

var missing_comma = [
    1,
    2,
]

Actual Output

js-beautify instead removes all trailing/dangling commas.

var x = [
    1,
    2,
    3
];

var y = {
   a: 1,
   b: 2,
   b: 3
];

var missing_comma = [
    1,
    2
]

Steps to Reproduce

Run js-beautify on any file containing the syntax in the example.

Environment

OS: Linux

Settings

I want a new setting for this. The current settings are irrelevant.

javascript enhancement

Most helpful comment

Is it possible to add this option? I went searching for it, and realised that I already added an issue a few months ago.

All 8 comments

Is it possible to add this option? I went searching for it, and realised that I already added an issue a few months ago.

"end_with_comma": true,

I suppose that's what the option could be called.

I would personally like to have js-beautify _add_ in my trailing commas and have babel remove them.

FYI: js-beautify does not remove trailing commas. If it ever did, it should not have and does not do so now.

At this time, the beautifier is a whitespace-only formatter.

Seconded, this is really the only dearly missed feature for me.
Makes a world of a difference for version control!

This seems like a moderate difficulty task.

PR's are welcome but it will need some design discussion - this would be a change in philosophy for
this project. There will also need to be extensive tests.

On second thought, I actually agree with @bitwiseman. This formatter is not for that, and if you want a tool that does that, you should check out a more opinionated formatter like prettier or eslint.

Was this page helpful?
0 / 5 - 0 ratings