更新 4
检查prettier,不是可以配置成esformatter,但是目前用来格式化一些大项目(like React itself)
更新 3
检查sublime jsfmt。如果您将esformatter-jsx 添加到配置中并在forlder 中为sublime-jsfmt 安装包。您将能够直接从 Sublime 格式化 JSX 文件。 Here is a guide for that
更新 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
这是live demo on 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 语法(基本上美化所有 javascript 语法并忽略 jsx 标记,即保持原样保留它们)的同时格式化您的 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 版本,以避免代理查询。