Fantastico modulo comunitario

JS Abbellitore

Stato di costruzione Stato di costruzione

Versione PyPI Versione CDNJS Versione NPM Scarica statistiche

Unisciti alla chat su https://gitter.im/beautify-web/js-beautify Twitter Segui

Statistiche NPM

Questo piccolo abbellitore riformatterà e reindenterà bookmarklet, brutto JavaScript, decomprimerà gli script impacchettati dal popolare packer di Dean Edward, nonché deoffuscherà gli script elaborati da javascriptobfuscator.com .

Collaboratori necessari

Lo metto in primo piano e al centro perché i proprietari esistenti hanno un tempo molto limitato per lavorare su questo progetto al momento. Questo è un progetto popolare e ampiamente utilizzato, ma ha un disperato bisogno di contributori che abbiano il tempo di impegnarsi a correggere sia i bug che i clienti devono affrontare sia i problemi sottostanti con la progettazione interna e la realizzazione.

Se sei interessato, dai un'occhiata alCONTRIBUTING.mdquindi risolvi un problema contrassegnato con l' etichetta "Buon primo problema" e invia un PR. Ripeti il ​​più spesso possibile. Grazie!

Utilizzo

Puoi abbellire javascript usando JS Beautifier nel tuo browser web o sulla riga di comando usando node.js o python.

JS Beautifier è ospitato su due servizi CDN: cdnjs e rawgit.

Per eseguire il pull da uno di questi servizi, includi una serie di tag di script di seguito nel documento:

1 2 3 4 5 6 7 8 9 10 11
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-css.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-html.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-css.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-html.min.js"></script> <script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.7.5/js/lib/beautify.js"></script> <script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.7.5/js/lib/beautify-css.js"></script> <script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.7.5/js/lib/beautify-html.js"></script>

Dichiarazione di non responsabilità: si tratta di servizi gratuiti, quindi non ci sono tempi di attività o garanzie di supporto .

Programma di navigazione in rete

Aprire jsbeautifier.org Le opzioni sono disponibili tramite l'interfaccia utente.

Pitone

Per abbellire usando Python:

1 2
$ pip install jsbeautifier $ js-beautify file.js

L'output abbellito va a stdout.

Usare jsbeautifiercome libreria è semplice:

1 2 3
import jsbeautifier res = jsbeautifier.beautify('your javascript string') res = jsbeautifier.beautify_file('some_file.js')

...oppure, per specificare alcune opzioni:

1 2 3 4
opts = jsbeautifier.default_options() opts.indent_size = 2 opts.space_in_empty_paren = True res = jsbeautifier.beautify('some javascript', opts)

I nomi delle opzioni di configurazione sono gli stessi dei nomi della CLI ma con caratteri di sottolineatura anziché trattini.L'esempio precedente dovrebbe essere impostato sulla riga di comando come --indent-size 2 --space-in-empty-paren.

javascript

In alternativa allo script Python, puoi installare il pacchetto NPM js-beautify.Se installato a livello globale, fornisce uno js-beautifyscript eseguibile.Come con lo script Python, il risultato abbellito viene inviato a stdoutse non diversamente configurato.

1 2
$ npm -g install js-beautify $ js-beautify foo.js

Puoi anche usare js-beautifycome nodelibreria (installa localmente, l' npmimpostazione predefinita):

1
$ npm install js-beautify

Importa e chiama il metodo di abbellimento appropriato per javascript (js), css o html. Tutte e tre le firme del metodo sono beautify(code, options). codeè una stringa di codice da abbellire. options è un oggetto con le impostazioni che vorresti utilizzare per abbellire il codice.

I nomi delle opzioni di configurazione sono gli stessi dei nomi dell'interfaccia della riga di comando, ma con caratteri di sottolineatura anziché trattini, ad esempio --indent-size 2 --space-in-empty-parensarebbe { indent_size: 2, space_in_empty_paren: true }.

1 2 3 4 5 6 7 8 9
var beautify = require('js-beautify').js, fs = require('fs'); fs.readFile('foo.js', 'utf8', function (err, data) { if (err) { throw err; } console.log(beautify(data, { indent_size: 2, space_in_empty_paren: true })); });

Opzioni

Questi sono i flag della riga di comando per gli script Python e JS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
CLI Options: -f, --file Input file(s) (Pass '-' for stdin) -r, --replace Write output in-place, replacing input -o, --outfile Write output to file (default stdout) --config Path to config file --type [js|css|html] ["js"] -q, --quiet Suppress logging to stdout -h, --help Show this help -v, --version Show the version Beautifier Options: -s, --indent-size Indentation size [4] -c, --indent-char Indentation character [" "] -t, --indent-with-tabs Indent with tabs, overrides -s and -c -e, --eol Character(s) to use as line terminators. [first newline in file, otherwise "\n] -n, --end-with-newline End output with newline --editorconfig Use EditorConfig to set up the options -l, --indent-level Initial indentation level [0] -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables) -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10] -P, --space-in-paren Add padding spaces within paren, ie. f( a, b ) -E, --space-in-empty-paren Add a single space inside empty paren, ie. f( ) -j, --jslint-happy Enable jslint-stricter mode -a, --space-after-anon-function Add a space before an anonymous function's parens, ie. function () -b, --brace-style [collapse|expand|end-expand|none][,preserve-inline] [collapse,preserve-inline] -u, --unindent-chained-methods Don't indent chained method calls -B, --break-chained-methods Break chained method calls across subsequent lines -k, --keep-array-indentation Preserve array indentation -x, --unescape-strings Decode printable characters encoded in xNN notation -w, --wrap-line-length Wrap lines at next opportunity after N characters [0] -X, --e4x Pass E4X xml literals through untouched --good-stuff Warm the cockles of Crockford's heart -C, --comma-first Put commas at the beginning of new line instead of end -O, --operator-position Set operator position (before-newline|after-newline|preserve-newline) [before-newline]

Che corrisponde alle chiavi di opzione sottolineate per entrambe le interfacce della libreria

impostazioni predefinite per le opzioni della CLI

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
{ "indent_size": 4, "indent_char": " ", "indent_with_tabs": false, "eol": "\n", "end_with_newline": false, "indent_level": 0, "preserve_newlines": true, "max_preserve_newlines": 10, "space_in_paren": false, "space_in_empty_paren": false, "jslint_happy": false, "space_after_anon_function": false, "brace_style": "collapse", "unindent_chained_methods": false, "break_chained_methods": false, "keep_array_indentation": false, "unescape_strings": false, "wrap_line_length": 0, "e4x": false, "comma_first": false, "operator_position": "before-newline" }

valori predefiniti non esposti nel cli

1 2 3 4
{ "eval_code": false, "space_before_conditional": true }

Nota che non tutte le impostazioni predefinite vengono esposte tramite l'interfaccia a riga di comando. Storicamente, le API Python e JS non sono state identiche al 100%. Ad esempio, attualmente è space_before_conditionalsolo JS e non è indirizzabile dallo script dell'interfaccia a riga di comando. Ci sono ancora alcuni altri casi che vengono mantenuti us dalla compatibilità API al 100%.

Loading settings from environment or .jsbeautifyrc (JavaScript-Only)

Oltre agli argomenti della CLI, puoi passare la configurazione all'eseguibile JS tramite:

  • qualsiasi jsbeautify_variabile di ambiente con prefisso
  • un JSONfile -formattato indicato dal --configparametro
  • un .jsbeautifyrcfile contenente JSONdati a qualsiasi livello del filesystem sopra$PWD

Le origini di configurazione fornite in precedenza in questo stack sovrascriveranno quelle successive.

Setting inheritance and Language-specific overrides

Le impostazioni sono un albero superficiale i cui valori sono ereditati per tutte le lingue, ma possono essere sovrascritti.Questo funziona per le impostazioni passate direttamente all'API in entrambe le implementazioni.Nell'implementazione Javascript, le impostazioni vengono caricate da un file di configurazione, come .jsbeautifyrc , può anche usare l'ereditarietà/l'override.

Di seguito è riportato un albero di configurazione di esempio che mostra tutte le posizioni supportate per i nodi di override della lingua. Useremo indent_sizeper discutere come si comporterebbe questa configurazione, ma qualsiasi numero di impostazioni può essere ereditato o sovrascritto:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{ "indent_size": 4, "html": { "end_with_newline": true, "js": { "indent_size": 2 }, "css": { "indent_size": 2 } }, "css": { "indent_size": 1 }, "js": { "preserve-newlines": true } }

L'utilizzo dell'esempio precedente avrebbe il seguente risultato:

  • File HTML
    • Eredita indent_sizedi 4 spazi dall'impostazione di primo livello.
    • I file finirebbero anche con una nuova riga.
    • JavaScript e CSS all'interno di HTML
      • Eredita l' end_with_newlineimpostazione HTML
      • Sostituisci il loro rientro a 2 spazi
  • File CSS
    • Sostituisci l'impostazione di primo livello su uno indent_sizespazio di 1.
  • File javascript
    • Eredita indent_sizedi 4 spazi dall'impostazione di primo livello
    • Impostare preserve-newlinessutrue

CSS & HTML

Oltre all'eseguibile js-beautify, css-beautifye html-beautify sono anche forniti come semplice interfaccia in quegli script.In alternativa, js-beautify --csso js-beautify --htmleseguiranno rispettivamente la stessa cosa.

1 2 3 4 5 6
// Programmatic access var beautify_js = require('js-beautify'); // also available under "js" export var beautify_css = require('js-beautify').css; var beautify_html = require('js-beautify').html; // All methods accept two arguments, the string to be beautified, and an options object.

Gli abbellitori CSS e HTML hanno un ambito molto più semplice e possiedono molte meno opzioni.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
CSS Beautifier Options: -s, --indent-size Indentation size [4] -c, --indent-char Indentation character [" "] -t, --indent-with-tabs Indent with tabs, overrides -s and -c -e, --eol Character(s) to use as line terminators. (default newline - "\\n") -n, --end-with-newline End output with newline -L, --selector-separator-newline Add a newline between multiple selectors -N, --newline-between-rules Add a newline between CSS rules HTML Beautifier Options: -s, --indent-size Indentation size [4] -c, --indent-char Indentation character [" "] -t, --indent-with-tabs Indent with tabs, overrides -s and -c -e, --eol Character(s) to use as line terminators. (default newline - "\\n") -n, --end-with-newline End output with newline -p, --preserve-newlines Preserve existing line-breaks (--no-preserve-newlines disables) -m, --max-preserve-newlines Maximum number of line-breaks to be preserved in one chunk [10] -I, --indent-inner-html Indent <head> and <body> sections. Default is false. -b, --brace-style [collapse-preserve-inline|collapse|expand|end-expand|none] ["collapse"] -S, --indent-scripts [keep|separate|normal] ["normal"] -w, --wrap-line-length Maximum characters per line (0 disables) [250] -A, --wrap-attributes Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline] ["auto"] -i, --wrap-attributes-indent-size Indent wrapped attributes to after N characters [indent-size] (ignored if wrap-attributes is "force-aligned") -U, --unformatted List of tags (defaults to inline) that should not be reformatted -T, --content_unformatted List of tags (defaults to pre) whose content should not be reformatted -E, --extra_liners List of tags (defaults to [head,body,/html] that should have an extra newline before them. --editorconfig Use EditorConfig to set up the options

Direttive per ignorare o preservare le sezioni (solo Javascript)

L'abbellitore per supporta le direttive nei commenti all'interno del file. Ciò consente di indicare all'abbellitore di conservare la formattazione o di ignorare completamente una parte di un file. L'input di esempio riportato di seguito rimarrà modificato dopo l'abbellimento

1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Use preserve when the content is not javascript, but you don't want it reformatted. /* beautify preserve:start */ { browserName: 'internet explorer', platform: 'Windows 7', version: '8' } /* beautify preserve:end */ // Use ignore when the content is not parsable as javascript. var a = 1; /* beautify ignore:start */ {This is some strange{template language{using open-braces? /* beautify ignore:end */

Licenza

Sei libero di usarlo nel modo che preferisci, nel caso in cui lo trovi utile o funzionante per te, ma devi conservare l'avviso di copyright e la licenza. (MIT)

Crediti

Grazie anche a Jason Diamond, Patrick Hof, Nochum Sossonko, Andreas Schneider, Dave Vasilevsky, Vital Batmanov, Ron Baldwin, Gabriel Harrison, Chris J. Shull, Mathias Bynens, Vittorio Gambaletta e altri.

(LEGGIMI.md: js-beautify@1.7.5)