UNPKG

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