• Stars
    star
    970
  • Rank 47,174 (Top 1.0 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ECMAScript code beautifier/formatter

esformatter

Build Status

ECMAScript code beautifier/formatter.

Important

This tool is still missing support for many important features. Please report any bugs you find, the code is only as good as the test cases. Feature requests are very welcome.

We are looking for contributors!!

Why?

jsbeautifier.org doesn't have enough options and not all IDEs/Editors have a good JavaScript code formatter. I would like to have a command line tool (and standalone lib) at least as powerful/flexible as the WebStorm and FDT code formatters so that it can be plugged into any editor and reused by other tools like escodegen.

For more reasoning behind it and history of the project see: esformatter & rocambole

How?

This tool uses rocambole and babylon to recursively parse the tokens and transform it in place.

Goals

  • granular control about white spaces, indent and line breaks.
  • command line interface (cli).
  • be non-destructive.
  • support for local/global config file so settings can be shared between team members.
  • be extensive (plugins and other cli tools).
  • support most popular style guides through plugins (Google, jQuery, Idiomatic.js).
  • be the best JavaScript code formatter!

API

var esformatter = require('esformatter');
var fs = require('fs');
var codeStr = fs.readFileSync('path/to/js/file.js').toString();

// for a list of available options check "lib/preset/default.js"
var options = {
  indent : {
    value : '  '
  },
  lineBreak : {
    before : {
      // at least one line break before BlockStatement
      BlockStatement : '>=1',
      // only one line break before DoWhileStatementOpeningBrace
      DoWhileStatementOpeningBrace : 1,
      // ...
    }
  },
  whiteSpace : {
    // ...
  }
};

// return a string with the formatted code
var formattedCode = esformatter.format(codeStr, options);

See the doc/api.md file for a list of all the public methods and detailed documentation about each one.

See doc/config.md for more info about the configuration options.

CLI

You can also use the simple command line interface to process the stdin or read from a file.

npm install [-g] esformatter

Usage:

Pass the --help flag to see the available options or see doc/cli.txt.

esformatter --help

Examples:

# Format
# ======

# format "test.js" and output result to stdout
esformatter test.js
# you can also pipe other shell commands (read file from stdin)
cat test.js | esformatter
# format "test.js" using options in "options.json" and output result to stdout
esformatter --config options.json test.js
# process "test.js" and writes to "test.out.js"
esformatter test.js > test.out.js
# you can override the default settings, see lib/preset/default.js for
# a list of available options
esformatter test.js --indent.value="\t" --lineBreak.before.IfStatementOpeningBrace=0
# format "test.js" and output result to "test.js"
esformatter -i test.js
# format and overwrite all the ".js" files inside the "lib/" folder
esformatter -i 'lib/*.js'
# format and overwrite all the ".js" files inside "lib/" and it's subfolders
esformatter -i 'lib/**/*.js'

# **important:** surround the glob with single quotes to avoid expansion; [glob
# syntax reference](https://github.com/isaacs/node-glob/#glob-primer)

# Diff
# ======

# check if "test.js" matches style and output diff to stdout
esformatter --diff test.js
# check if "test.js" matches style and output unified diff to stdout
esformatter --diff-unified test.js
# check if "test.js" matches "options.json" style and output diff to stdout
esformatter --diff --config options.json test.js
# check all files inside "lib/" and it's subfolders
esformatter --diff 'lib/**/*.js'

Local version

If a locally installed esformatter is found, the CLI uses that instead of the global executable (this means you can have multiple projects depending on different versions of esformatter).

protip: add esformatter and all the plugins that you need on your project to the package.json devDependencies that way you can use locally installed plugins and also make sure everyone on your team is using the same version/settings.

{
  "devDependencies": {
    "esformatter": "~0.6.0",
    "esformatter-quotes": "^1.0.1"
  },
  "esformatter": {
    "plugins": ["esformatter-quotes"],
    "quotes": {
      "type": "single"
    }
  }
}

IDE / Editor integration

Since esformatter is available as a command-line tool, it can be used in any editor that supports external shell commands.

Configuration

See doc/config.md.

Presets

Presets are reusable config files that can require other presets/plugins and override configs.

{
  // presets are used as "base settings"
  "extends": [
    "preset:foobar", // load "esformatter-preset-foobar" from "./node_modules"
    "./lorem_ipsum.json" // load relative config file
  ],

  // you can still override any setting from the preset if needed
  "indent": {
    "value": "  "
  }
}

For more info see presets.md

Pipe other CLI tools

Since we don't expect everyone to write plugins that only works with esformatter we decided to encourage the usage of standalone CLI tools.

{
  // pipe is a simple way to "pipe" multiple binaries input/output
  "pipe": {
    // scripts listed as "before" will be executed before esformatter
    // and will forward output to next command in the queue
    "before": [
      "strip-debug",
      "./bin/my-custom-script.sh --foo true -zx"
    ],
    // scripts listed as "after" will be executed after esformatter
    "after": [
      "baz --keepLineBreaks"
    ]
  }
}

Plugins

Plugins are automatically loaded from node_modules if you pass the module id in the config file:

{
  "plugins": [ "esformatter-sample-plugin", "foobar" ]
}

List of plugins and plugins wish list: https://github.com/millermedeiros/esformatter/wiki/Plugins

List of plugins with easy filterable search: http://pgilad.github.io/esformatter-plugins/

For detailed information about plugins structure and API see doc/plugins.md

IRC

We have an IRC channel #esformatter on irc.freenode.net for quick discussions about the project development/structure.

Wiki

See project Wiki for more info: https://github.com/millermedeiros/esformatter/wiki

Project structure / Contributing

See CONTRIBUTING.md

Popular Alternatives

License

Released under the MIT license

More Repositories

1

js-signals

Custom Event/Messaging system for JavaScript inspired by AS3-Signals
JavaScript
1,959
star
2

crossroads.js

JavaScript Routes
JavaScript
1,445
star
3

requirejs-plugins

RequireJS Plugins
JavaScript
932
star
4

Hasher

Browser history manager for rich media websites
JavaScript
492
star
5

mdoc

node.js markdown powered documentation generator
CSS
202
star
6

rocambole

Recursively walk and transform EcmaScript AST
JavaScript
171
star
7

amd-utils

modular JavaScript utilities written in the AMD format
JavaScript
143
star
8

vim-statline

Add useful informations to Vim statusline
Vim Script
83
star
9

gh-markdown-cli

Node.js command-line tool to batch convert Markdown files into HTML
JavaScript
81
star
10

requirejs-hogan-plugin

RequireJS Hogan / Mustache Plugin
JavaScript
77
star
11

nodefy

convert AMD modules into a node.js compatible format
JavaScript
64
star
12

disparity

colorized string diff (char or unified) ideal for text/code that spans through multiple lines
JavaScript
56
star
13

vim-esformatter

run esformatter from inside vim (automatically formats JavaScript source code)
Vim Script
34
star
14

basis.css

A base CSS stylesheet for rapid development
31
star
15

CompoundSignal

Special Signal type used to listen for multiple Signals dispatches
JavaScript
31
star
16

node-ant

Experimental Apache Ant adapter for node.js
Shell
27
star
17

esformatter-quotes

esformatter plugin: enforces coding style that string literals are delimited with single or double quotes
JavaScript
26
star
18

domr

fast and async DOM updates for modern browsers
JavaScript
21
star
19

swffit

swffit repository
JavaScript
17
star
20

SVGParser

AS3 SVG parser to FIVe3D and HTML5 canvas
ActionScript
16
star
21

MM_js_lib

My Modular JavaScript Library
JavaScript
16
star
22

trainwreck.js

JavaScript method chaining made easy
JavaScript
15
star
23

MM_boilerplate

My Basic Project Boilerplate
JavaScript
13
star
24

CanvasContext2DWrapper

enable Canvas method chaining without overwritting any native objects/prototypes
JavaScript
13
star
25

esindent

[deprecated] ECMAScript code indenter based on Esprima AST and Rocambole
JavaScript
6
star
26

rocambole-token

Helpers for rocambole AST token manipulation
JavaScript
5
star
27

prototype-week-view

prototype for gaia calendar v2.1
JavaScript
5
star
28

Hasher_AS3_helper

Actionscript 3 helper classes to use together with Hasher.js
JavaScript
4
star
29

rtf.js

JavaScript RTF document generator
4
star
30

rocambole-node

Helpers for rocambole AST node manipulation
JavaScript
4
star
31

esformatter-semicolon-first

esformatter plugin to add semicolon before `[` and `(` if they are the first things on the line
JavaScript
3
star
32

esformatter-flow

esformatter plugin: enforces coding style for Flow type annotations
JavaScript
3
star
33

MM_php_lib

My Modular PHP5 Library
PHP
3
star
34

MM_as3_lib

My Modular AS3 Library
ActionScript
3
star
35

eclipse_monkey_scripts

Scripts for extending Eclipse and Aptana functionalities through the Eclipse Monkey plugin.
JavaScript
3
star
36

SceneGraph.js

[abandoned] JavaScript implementation of a Scene Graph (a.k.a. display list) initially targeting HTML5 canvas but with plans to support other rendering engines in the future.
3
star
37

esformatter-parser

JavaScript parser used by esformatter (babylon+rocambole)
JavaScript
1
star
38

rocambole-linebreak

helpers to manipulate rocambole AST line break tokens
JavaScript
1
star
39

rocambole-whitespace

helpers for rocambole AST whitespace manipulation
JavaScript
1
star
40

YUI_to_Jasmine

Simple tool to convert YUI Test assertions into Jasmine expect() calls
JavaScript
1
star
41

rocambole-indent

helpers for rocambole AST indentation
JavaScript
1
star