UNPKG

16.4 kBMarkdownView Raw
1# JS Beautifier
2[![Build Status](https://api.travis-ci.org/beautify-web/js-beautify.svg?branch=master)](http://travis-ci.org/beautify-web/js-beautify)
3[![Build status](https://ci.appveyor.com/api/projects/status/5bxmpvew5n3e58te/branch/master?svg=true)](https://ci.appveyor.com/project/beautify-web/js-beautify/branch/master)
4
5[![PyPI version](https://img.shields.io/pypi/v/jsbeautifier.svg)](https://pypi.python.org/pypi/jsbeautifier)
6[![CDNJS version](https://img.shields.io/cdnjs/v/js-beautify.svg)](https://cdnjs.com/libraries/js-beautify)
7[![NPM @latest](https://img.shields.io/npm/v/js-beautify.svg)](https://www.npmjs.com/package/js-beautify)
8[![NPM @next](https://img.shields.io/npm/v/js-beautify/next.svg)](https://www.npmjs.com/package/js-beautify?activeTab=versions)
9
10[![Join the chat at https://gitter.im/beautify-web/js-beautify](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/beautify-web/js-beautify?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
11[![Twitter Follow](https://img.shields.io/twitter/follow/js_beautifier.svg?style=social&label=Follow)](https://twitter.com/intent/user?screen_name=js_beautifier)
12
13[![NPM stats](https://nodei.co/npm/js-beautify.svg?downloadRank=true&downloads=true)](https://www.npmjs.org/package/js-beautify)
14
15
16This little beautifier will reformat and re-indent bookmarklets, ugly
17JavaScript, unpack scripts packed by Dean Edward’s popular packer,
18as well as partly deobfuscate scripts processed by the npm package
19[javascript-obfuscator](https://github.com/javascript-obfuscator/javascript-obfuscator).
20
21Open [beautifier.io](https://beautifier.io/) to try it out. Options are available via the UI.
22
23# Contributors Needed
24I'm putting this front and center above because existing owners have very limited time to work on this project currently.
25This is a popular project and widely used but it desperately needs contributors who have time to commit to fixing both
26customer facing bugs and underlying problems with the internal design and implementation.
27
28If you are interested, please take a look at the [CONTRIBUTING.md](https://github.com/beautify-web/js-beautify/blob/master/CONTRIBUTING.md) then fix an issue marked with the ["Good first issue"](https://github.com/beautify-web/js-beautify/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) label and submit a PR. Repeat as often as possible. Thanks!
29
30
31# Installation
32
33You can install the beautifier for node.js or python.
34
35## Node.js JavaScript
36
37You may install the NPM package `js-beautify`. When installed globally, it provides an executable `js-beautify` script. As with the Python script, the beautified result is sent to `stdout` unless otherwise configured.
38
39```bash
40$ npm -g install js-beautify
41$ js-beautify foo.js
42```
43
44You can also use `js-beautify` as a `node` library (install locally, the `npm` default):
45
46```bash
47$ npm install js-beautify
48```
49
50## Node.js JavaScript (vNext)
51
52The above install the latest stable release. To install beta or RC versions:
53
54```bash
55$ npm install js-beautify@next
56```
57
58## Web Library
59The beautifier can be added on your page as web library.
60
61JS Beautifier is hosted on two CDN services: [cdnjs](https://cdnjs.com/libraries/js-beautify) and rawgit.
62
63To pull the latest version from one of these services include one set of the script tags below in your document:
64```html
65<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify.js"></script>
66<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify-css.js"></script>
67<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify-html.js"></script>
68
69<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify.min.js"></script>
70<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify-css.min.js"></script>
71<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.8.5/beautify-html.min.js"></script>
72
73<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.8.5/js/lib/beautify.js"></script>
74<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.8.5/js/lib/beautify-css.js"></script>
75<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.8.5/js/lib/beautify-html.js"></script>
76```
77
78Older versions are available by changing the version number.
79
80Disclaimer: These are free services, so there are [no uptime or support guarantees](https://github.com/rgrove/rawgit/wiki/Frequently-Asked-Questions#i-need-guaranteed-100-uptime-should-i-use-cdnrawgitcom).
81
82
83## Python
84To install the Python version of the beautifier:
85
86```bash
87$ pip install jsbeautifier
88```
89
90
91# Usage
92You can beautify javascript using JS Beautifier in your web browser, or on the command-line using node.js or python.
93
94## Web Browser
95Open [beautifier.io](https://beautifier.io/). Options are available via the UI.
96
97## Web Libary
98The script tags above expose three functions: `js_beautify`, `css_beautify`, and `html_beautify`.
99
100## Node.js JavaScript
101
102When installed globally, the beautifier provides an executable `js-beautify` script. The beautified result is sent to `stdout` unless otherwise configured.
103
104```bash
105$ js-beautify foo.js
106```
107
108To use `js-beautify` as a `node` library (after install locally), import and call the appropriate beautifier method for javascript (js), css, or html. All three method signatures are `beautify(code, options)`. `code` is the string of code to be beautified. options is an object with the settings you would like used to beautify the code.
109
110The configuration option names are the same as the CLI names but with underscores instead of dashes. For example, `--indent-size 2 --space-in-empty-paren` would be `{ indent_size: 2, space_in_empty_paren: true }`.
111
112```js
113var beautify = require('js-beautify').js,
114 fs = require('fs');
115
116fs.readFile('foo.js', 'utf8', function (err, data) {
117 if (err) {
118 throw err;
119 }
120 console.log(beautify(data, { indent_size: 2, space_in_empty_paren: true }));
121});
122```
123
124## Python
125After installing, to beautify using Python:
126
127```bash
128$ js-beautify file.js
129```
130
131Beautified output goes to `stdout` by default.
132
133To use `jsbeautifier` as a library is simple:
134
135```python
136import jsbeautifier
137res = jsbeautifier.beautify('your javascript string')
138res = jsbeautifier.beautify_file('some_file.js')
139```
140
141...or, to specify some options:
142
143```python
144opts = jsbeautifier.default_options()
145opts.indent_size = 2
146opts.space_in_empty_paren = True
147res = jsbeautifier.beautify('some javascript', opts)
148```
149
150The configuration option names are the same as the CLI names but with underscores instead of dashes. The example above would be set on the command-line as `--indent-size 2 --space-in-empty-paren`.
151
152
153# Options
154
155These are the command-line flags for both Python and JS scripts:
156
157```text
158CLI Options:
159 -f, --file Input file(s) (Pass '-' for stdin)
160 -r, --replace Write output in-place, replacing input
161 -o, --outfile Write output to file (default stdout)
162 --config Path to config file
163 --type [js|css|html] ["js"]
164 -q, --quiet Suppress logging to stdout
165 -h, --help Show this help
166 -v, --version Show the version
167
168Beautifier Options:
169 -s, --indent-size Indentation size [4]
170 -c, --indent-char Indentation character [" "]
171 -t, --indent-with-tabs Indent with tabs, overrides -s and -c
172 -e, --eol Character(s) to use as line terminators.
173 [first newline in file, otherwise "\n]
174 -n, --end-with-newline End output with newline
175 --editorconfig Use EditorConfig to set up the options
176 -l, --indent-level Initial indentation level [0]
177 -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)
178 -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]
179 -P, --space-in-paren Add padding spaces within paren, ie. f( a, b )
180 -E, --space-in-empty-paren Add a single space inside empty paren, ie. f( )
181 -j, --jslint-happy Enable jslint-stricter mode
182 -a, --space-after-anon-function Add a space before an anonymous function's parens, ie. function ()
183 -b, --brace-style [collapse|expand|end-expand|none][,preserve-inline] [collapse,preserve-inline]
184 -u, --unindent-chained-methods Don't indent chained method calls
185 -B, --break-chained-methods Break chained method calls across subsequent lines
186 -k, --keep-array-indentation Preserve array indentation
187 -x, --unescape-strings Decode printable characters encoded in xNN notation
188 -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]
189 -X, --e4x Pass E4X xml literals through untouched
190 --good-stuff Warm the cockles of Crockford's heart
191 -C, --comma-first Put commas at the beginning of new line instead of end
192 -O, --operator-position Set operator position (before-newline|after-newline|preserve-newline) [before-newline]
193```
194
195Which correspond to the underscored option keys for both library interfaces
196
197**defaults per CLI options**
198```json
199{
200 "indent_size": 4,
201 "indent_char": " ",
202 "indent_with_tabs": false,
203 "eol": "\n",
204 "end_with_newline": false,
205 "indent_level": 0,
206 "preserve_newlines": true,
207 "max_preserve_newlines": 10,
208 "space_in_paren": false,
209 "space_in_empty_paren": false,
210 "jslint_happy": false,
211 "space_after_anon_function": false,
212 "brace_style": "collapse",
213 "unindent_chained_methods": false,
214 "break_chained_methods": false,
215 "keep_array_indentation": false,
216 "unescape_strings": false,
217 "wrap_line_length": 0,
218 "e4x": false,
219 "comma_first": false,
220 "operator_position": "before-newline"
221}
222```
223
224**defaults not exposed in the cli**
225```json
226{
227 "eval_code": false,
228 "space_before_conditional": true
229}
230```
231
232Notice not all defaults are exposed via the CLI. Historically, the Python and
233JS APIs have not been 100% identical. There are still a
234few other additional cases keeping us from 100% API-compatibility.
235
236
237## Loading settings from environment or .jsbeautifyrc (JavaScript-Only)
238
239In addition to CLI arguments, you may pass config to the JS executable via:
240
241 * any `jsbeautify_`-prefixed environment variables
242 * a `JSON`-formatted file indicated by the `--config` parameter
243 * a `.jsbeautifyrc` file containing `JSON` data at any level of the filesystem above `$PWD`
244
245Configuration sources provided earlier in this stack will override later ones.
246
247## Setting inheritance and Language-specific overrides
248
249The settings are a shallow tree whose values are inherited for all languages, but
250can be overridden. This works for settings passed directly to the API in either implementation.
251In the Javascript implementation, settings loaded from a config file, such as .jsbeautifyrc, can also use inheritance/overriding.
252
253Below is an example configuration tree showing all the supported locations
254for language override nodes. We'll use `indent_size` to discuss how this configuration would behave, but any number of settings can be inherited or overridden:
255
256```json
257{
258 "indent_size": 4,
259 "html": {
260 "end_with_newline": true,
261 "js": {
262 "indent_size": 2
263 },
264 "css": {
265 "indent_size": 2
266 }
267 },
268 "css": {
269 "indent_size": 1
270 },
271 "js": {
272 "preserve-newlines": true
273 }
274}
275```
276
277Using the above example would have the following result:
278
279* HTML files
280 * Inherit `indent_size` of 4 spaces from the top-level setting.
281 * The files would also end with a newline.
282 * JavaScript and CSS inside HTML
283 * Inherit the HTML `end_with_newline` setting.
284 * Override their indentation to 2 spaces.
285* CSS files
286 * Override the top-level setting to an `indent_size` of 1 space.
287* JavaScript files
288 * Inherit `indent_size` of 4 spaces from the top-level setting.
289 * Set `preserve-newlines` to `true`.
290
291## CSS & HTML
292
293In addition to the `js-beautify` executable, `css-beautify` and `html-beautify`
294are also provided as an easy interface into those scripts. Alternatively,
295`js-beautify --css` or `js-beautify --html` will accomplish the same thing, respectively.
296
297```js
298// Programmatic access
299var beautify_js = require('js-beautify'); // also available under "js" export
300var beautify_css = require('js-beautify').css;
301var beautify_html = require('js-beautify').html;
302
303// All methods accept two arguments, the string to be beautified, and an options object.
304```
305
306The CSS & HTML beautifiers are much simpler in scope, and possess far fewer options.
307
308```text
309CSS Beautifier Options:
310 -s, --indent-size Indentation size [4]
311 -c, --indent-char Indentation character [" "]
312 -t, --indent-with-tabs Indent with tabs, overrides -s and -c
313 -e, --eol Character(s) to use as line terminators. (default newline - "\\n")
314 -n, --end-with-newline End output with newline
315 -L, --selector-separator-newline Add a newline between multiple selectors
316 -N, --newline-between-rules Add a newline between CSS rules
317
318HTML Beautifier Options:
319 -s, --indent-size Indentation size [4]
320 -c, --indent-char Indentation character [" "]
321 -t, --indent-with-tabs Indent with tabs, overrides -s and -c
322 -e, --eol Character(s) to use as line terminators. (default newline - "\\n")
323 -n, --end-with-newline End output with newline
324 -p, --preserve-newlines Preserve existing line-breaks (--no-preserve-newlines disables)
325 -m, --max-preserve-newlines Maximum number of line-breaks to be preserved in one chunk [10]
326 -I, --indent-inner-html Indent <head> and <body> sections. Default is false.
327 -b, --brace-style [collapse-preserve-inline|collapse|expand|end-expand|none] ["collapse"]
328 -S, --indent-scripts [keep|separate|normal] ["normal"]
329 -w, --wrap-line-length Maximum characters per line (0 disables) [250]
330 -A, --wrap-attributes Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline|aligned-multiple] ["auto"]
331 -i, --wrap-attributes-indent-size Indent wrapped attributes to after N characters [indent-size] (ignored if wrap-attributes is "aligned")
332 -d, --inline List of tags to be considered inline tags
333 -U, --unformatted List of tags (defaults to inline) that should not be reformatted
334 -T, --content_unformatted List of tags (defaults to pre) whose content should not be reformatted
335 -E, --extra_liners List of tags (defaults to [head,body,/html] that should have an extra newline before them.
336 --editorconfig Use EditorConfig to set up the options
337```
338
339## Directives to Ignore or Preserve sections (Javascript beautifier only)
340
341Beautifier for supports directives in comments inside the file.
342This allows you to tell the beautifier to preserve the formatting of or completely ignore part of a file.
343The example input below will remain changed after beautification
344
345```js
346// Use preserve when the content is not javascript, but you don't want it reformatted.
347/* beautify preserve:start */
348{
349 browserName: 'internet explorer',
350 platform: 'Windows 7',
351 version: '8'
352}
353/* beautify preserve:end */
354
355// Use ignore when the content is not parsable as javascript.
356var a = 1;
357/* beautify ignore:start */
358 {This is some strange{template language{using open-braces?
359/* beautify ignore:end */
360```
361
362# License
363
364You are free to use this in any way you want, in case you find this useful or working for you but you must keep the copyright notice and license. (MIT)
365
366# Credits
367
368* Created by Einar Lielmanis, <einar@beautifier.io>
369* Python version flourished by Stefano Sanfilippo <a.little.coder@gmail.com>
370* Command-line for node.js by Daniel Stockman <daniel.stockman@gmail.com>
371* Maintained and expanded by Liam Newman <bitwiseman@beautifier.io>
372
373Thanks also to Jason Diamond, Patrick Hof, Nochum Sossonko, Andreas Schneider, Dave
374Vasilevsky, Vital Batmanov, Ron Baldwin, Gabriel Harrison, Chris J. Shull,
375Mathias Bynens, Vittorio Gambaletta and others.
376
377(README.md: js-beautify@1.8.5)