esformatter plugin: conditionally collapses objects and array literals
npm install esformatter-collapse-objectsesformatter plugin for
conditionally collapsing object and array literals.
install it:
``sh`
npm install esformatter-collapse-objects
and something like this to your esformatter config file:
`json`
{
"plugins": [
"esformatter-collapse-objects"
]
}
This plugin works by relying on esformatter expanding the relevant expressions,
and conditionally collapsing them back down to a single line. Therefore, you
need to have esformatter expand them in the first place (esformatter defaults to
expanding object literals, but not array literals).
Add the following to your esformatter config when collapsing arrays:
`json`
"lineBreak": {
"before": {
"ArrayExpressionClosing": 1
},
"after": {
"ArrayExpressionOpening": 1,
"ArrayExpressionComma": 1
}
},
Since expressions were collapsed, you might be surprised that some appear as
{a:b,c:d}. This is because esformatter defaults are tuned toward expanded
expressions. Try merging the following into your config for whitespace before
each property in an object:
`json`
{
"whiteSpace": {
"before": {
"PropertyName": 1
}
}
The following is the default configuration for the plugin, which can be reproduced
and modified in your .esformatter config:
`json
{
"collapseObjects": {
"ObjectExpression": {
"maxLineLength": 80,
"maxKeys": 3,
"maxDepth": 2,
"forbidden": [
"FunctionExpression"
]
},
"ArrayExpression": {
"maxLineLength": 80,
"maxKeys": 3,
"maxDepth": 2,
"forbidden": [
"FunctionExpression"
]
}
}
}
`
Options map esprima AST Node types (in this case both ObjectExpression and
ArrayExpression) to their respective options, just like indentation in
esformatter.
__Set either expression's value to -1 to opt out of collapsing those nodes.__
Use a maxLineLength of -1 to ignore this option.
`js`
[function foo() { return 'bar' }]
for example, could never occur since FunctionExpression is forbidden when
trying to collapse a literal if this is set.
Use a forbidden of [] to ignore this option.
has a depth of two and would be
collapsed if the maxDepth is 2 or greater.
Use a
maxDepth of -1 to opt out of this functionality.JavaScript API
Register the plugin and call esformatter like so:
`js
// register plugin
esformatter.register(require('esformatter-collapse-objects'));
// pass options as second argument
var output = esformatter.format(str, options);
``Released under the MIT License.
Huge thanks to Jörn Zaefferer, who published an MIT-licensed gist
which serves as the foundation for this module.