millermedeiros / esformatter

ECMAScript code beautifier/formatter
MIT License
970 stars 91 forks source link

Preserve line breaks for object initializers? #477

Closed langdonx closed 7 years ago

langdonx commented 7 years ago

Is this currently possible?

Single-line object intializers input someFn({a:true,b:false});

formatted output someFn({ a: true, b: false });

Multi-line object initializers input

someFn({
a:true,
b:false
});

formatted output

someFn({
    a: true,
    b: false
});

I'd like to only force multi-line object initializers if the source is multi-line. This is my best attempt by unfortunately adds whiteSpace before each comma:

{
  "preset": "default",
  "indent": {
    "value": " ",
    "FunctionExpression": 4,
    "MultipleVariableDeclaration": 4
  },
  "lineBreak": {
    "before": {
      "Property": "-1",
      "ObjectExpressionClosingBrace": "-1"
    },
    "after": {
      "ObjectExpressionOpeningBrace": "-1"
    }
  },
  "whiteSpace": {
    "after": {
      "PropertyValue": 1
    }
  }
}
langdonx commented 7 years ago

Using http://lloiser.github.io/esformatter-visualize/ with my config above

(function () {
    var singleLineResult,
        multilineResult;

    singleLineResult = { a: 1, c: 2 }; // exactly what i'm looking for
singleLineResult={a:1,c:2}; // no white space
              singleLineResult      =      {      a   :    1     ,     c   :    2      }; // lots of white space

    // exactly what i'm looking for
    multilineResult = {
        a: 1,
        c: 2
    };

    // no whitespace
multilineResult={
a:1,
c:2
};

    // lots of whitespace
        multilineResult           =      {
             a    :     1       , 
        c     :    2
             }   ;

     // pie in the sky mismatch (if there's any line break, it should force the entire initialize to use line breaks)
    multilineResult = { a: 1, b: 2,
        c: 2
    };
    multilineResult = {
        a: 1, b: 2, c: 2
    };
}());

The result is this:

image

millermedeiros commented 7 years ago

the version on https://github.com/lloiser/esformatter-visualize/ is like 2 years old..

I believe we support this already, see:

millermedeiros commented 7 years ago

you can find what are the available options for object expressions here: https://github.com/millermedeiros/esformatter/blob/master/lib/hooks/ObjectExpression.js (search for limit)

millermedeiros commented 7 years ago

there is also a plugin that toggles the object line breaks based on the size: https://github.com/wbinnssmith/esformatter-collapse-objects