我正在使用Sublime Text作为文本编辑器。
有一种用于格式化JavaScript文件的jsFormat,但我找不到用于JSX的格式。
你们如何处理JSX格式?
更新4
检查更漂亮,不是可配置为esformatter,但当前用于格式化一些大型项目(例如React本身)
更新3
检查sublime jsfmt。如果将esformatter- jsx添加到配置中,然后将软件包安装在forlime- jsfmt的forlder中。您将能够直接从Sublime格式化JSX文件。这是为此的指南
更新2
在命令行中,您也可以使用esbeautifier。它是esformatter的包装,它接受要格式化的glob列表
# install the dependencies globally npm i -g esbeautifier # beautify the files under src/ and specs/ both .js and .jsx esbeautifier src/**/*.js* specs/**/*.js*
更新资料
因此,我最终为esformatter做了一个插件来启用JSX文件的格式设置:
https://www.npmjs.com/package/esformatter- jsx
这是在requirebin上的现场演示
从Sublime 调用esformatter并传递当前文件作为参数应该是可行的。无论如何从命令行使用它,都可以按照以下说明进行:
在命令行中,可以这样使用它:
# install the dependencies globally npm i -g esformatter esformatter-jsx # call it (this will print to stdout) esformatter --plugins=esformatter-jsx ./path/to/your/file # to actually modify the file esformatter --plugins=esformatter-jsx ./path/to/your/file > ./path/to/your/file # to specify a config file (where you can also specify the plugins) # check esformatter for more info about the configuration options esformatter -c ./path/to/.esformatter ./path/to/your/file > ./path/to/your/file
====下面的旧答案===
因此,如果您只是想在允许jsx语法的情况下格式化jsx文件(基本上是美化所有javascript语法并忽略jsx标签,这意味着将它们保留原样),这就是我正在使用的方法esformatter
jsx
esformatter
// needed for grunt.file.expand var grunt = require('grunt'); // use it with care, I haven't check if there // isn't any side effect from using proxyquire to // inject esprima-fb into the esformatter // but this type of dependency replacement // seems to be very fragile... if rocambole deps change // this will certainly break, same is true for esformatter // use it with care var proxyquire = require('proxyquire'); var rocambole = proxyquire('rocambole', { 'esprima': require('esprima-fb') }); var esformatter = proxyquire('esformatter', { rocambole: rocambole }); // path to your esformatter configuration var cfg = grunt.file.readJSON('./esformatter.json'); // expand the files from the glob var files = grunt.file.expand('./js/**/*.jsx'); // do the actual formatting files.forEach(function (fIn) { console.log('formatting', fIn); var output = esformatter.format(grunt.file.read(fIn), cfg); grunt.file.write(fIn, output); });
我实际上希望esformatter使用使用esprima-fb而不是esprima的rocambole版本,以避免proxyquire。