esformatter plugin: format javascript files that contain React JSX blocks

Demo
Live demo: esformatter-jsx
Usage with JSFMT
check this guide
best configuration
If you're running into troubles with the formatting applied to your files I found this configuration to work the best:
{
"jsx": {
"formatJSX": true,
"attrsOnSameLineAsTag": false,
"maxAttrsOnTag": 3,
"firstAttributeOnSameLine": true,
"formatJSXExpressions": true,
"JSXExpressionsSingleLine": true,
"alignWithFirstAttribute": false,
"spaceInJSXExpressionContainers": " ",
"removeSpaceBeforeClosingJSX": false,
"closingTagOnNewLine": false,
"JSXAttributeQuotes": "",
"htmlOptions": {
}
}
}
Overview
Esformatter-jsx is a plugin for esformatter meant to allow the
code formatting of jsx files or js files with React code blocks, using js-beautify to
beautify the "html like" syntax of the react components. Use at your own risk. I have tested this against complex JSX structures and seems to be workfing fine, but bugs might appear, so don't blame me :).
It works for my main use case and I hope it works for you too.
This plugin is based on esformatter-jsx-ignore
If you want a bit of history about what this plugin was develop, check:
So this plugin will turn this:
var React = require('react');
var Hello = React.createClass({
render: function () {
return (<div
className="hello-div">{this.props.message}</div>)
;
}
});
React.render(<Hello
message="world"/>, document.body);
into:
var React = require('react');
var Hello = React.createClass({
render: function() {
return (
<div className="hello-div">
{this.props.message}
</div>
);
}
});
React.render(<Hello message="world"/>, document.body);
Installation
$ npm install esformatter-jsx --save-dev
Config
Newest esformatter versions autoload plugins from your node_modules
See this
Add to your esformatter config file:
In order for this to work, this plugin should be the first one! (I Know too picky, but who isn't).
{
"plugins": [
"esformatter-jsx"
],
"jsx": {
"formatJSXExpressions": true,
"JSXExpressionsSingleLine": true,
"formatJSX": true,
"attrsOnSameLineAsTag": true,
"maxAttrsOnTag": 1,
"firstAttributeOnSameLine": false,
"spaceInJSXExpressionContainers": " ",
"alignWithFirstAttribute": true,
"htmlOptions": {
"brace_style": "collapse",
"indent_char": " ",
"indent_size": 2,
"max_preserve_newlines": 2,
"preserve_newlines": true
}
}
}
The htmlOptions
are passed directly to js-beautify, please check its
documentation for all the possible options.
Or you can manually register your plugin:
esformatter.register(require('esformatter-jsx'));
Usage
var fs = require('fs');
var esformatter = require('esformatter');
esformatter.register(require('esformatter-jsx'));
var str = fs.readFileSync('someKewlFile.js').toString();
var output = esformatter.format(str);
See esformatter for more options and further usage info.
License
MIT