Embellecedor JS
Este pequeño embellecedor reformateará y reintegrará marcadores, JavaScript feo, descomprimirá los scripts empaquetados por el popular empaquetador de Dean Edward, así como desofuscará los scripts procesados por javascriptobfuscator.com .
Se necesitan colaboradores
Estoy poniendo esto al frente y al centro arriba porque los propietarios existentes tienen un tiempo muy limitado para trabajar en este proyecto actualmente. Este es un proyecto popular y ampliamente utilizado, pero necesita desesperadamente colaboradores que tengan tiempo para comprometerse a solucionar tanto los errores que enfrentan los clientes como los problemas subyacentes. con el diseño e implementación internos.
Si está interesado, eche un vistazo a la CONTRIBUTING.mdluego solucione un problema marcado con la etiqueta "Buen primer problema" y envíe un PR. Repita con la mayor frecuencia posible. ¡Gracias!
Uso
Puede embellecer javascript usando JS Beautifier en su navegador web, o en la línea de comandos usando node.js o python.
JS Beautifier está alojado en dos servicios CDN: cdnjs y rawgit.
Para extraer de uno de estos servicios, incluya un conjunto de etiquetas de secuencia de comandos a continuación en su 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>
Descargo de responsabilidad: estos son servicios gratuitos, por lo que no hay garantías de tiempo de actividad ni de soporte .
Navegador web
Abra jsbeautifier.org . Las opciones están disponibles a través de la interfaz de usuario.
Pitón
Para embellecer usando Python:
1
2$ pip install jsbeautifier
$ js-beautify file.js
La salida embellecida va a stdout
.
Usar jsbeautifier
como biblioteca es simple:
1
2
3import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')
... o, para especificar algunas opciones:
1
2
3
4opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_empty_paren = True
res = jsbeautifier.beautify('some javascript', opts)
Los nombres de las opciones de configuración son los mismos que los de la CLI pero con guiones bajos en lugar de guiones. El ejemplo anterior se establecería en la línea de comandos como --indent-size 2 --space-in-empty-paren
.
JavaScript
Como alternativa a la secuencia de comandos de Python, puede instalar el paquete NPM js-beautify
. Cuando se instala globalmente, proporciona una js-beautify
secuencia de comandos ejecutable . Al igual que con la secuencia de comandos de Python, el resultado embellecido se envía a a stdout
menos que se configure lo contrario.
1
2$ npm -g install js-beautify
$ js-beautify foo.js
También puede usar js-beautify
como node
biblioteca (instalar localmente, el npm
valor predeterminado):
1$ npm install js-beautify
Importe y llame al método embellecedor apropiado para javascript (js), css o html. Las tres firmas de métodos son beautify(code, options)
. code
Es la cadena de código que se va a embellecer. Options es un objeto con la configuración que le gustaría usar para embellecer el código.
Los nombres de las opciones de configuración son los mismos que los de la CLI pero con guiones bajos en lugar de guiones. Por ejemplo, --indent-size 2 --space-in-empty-paren
sería { indent_size: 2, space_in_empty_paren: true }
.
1
2
3
4
5
6
7
8
9var 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 }));
});
Opciones
Estos son los indicadores de la línea de comandos para los scripts de Python y 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
35CLI 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]
Que corresponden a las claves de opción subrayadas para ambas interfaces de biblioteca
valores predeterminados según las opciones de 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"
}
valores predeterminados no expuestos en el cli
1
2
3
4{
"eval_code": false,
"space_before_conditional": true
}
Tenga en cuenta que no todos los valores predeterminados se exponen a través de la CLI. Históricamente, las API de Python y JS no han sido 100% idénticas. Por ejemplo, space_before_conditional
actualmente es solo JS y no se puede direccionar desde la secuencia de comandos de la CLI. Todavía hay algunos otros casos adicionales que se mantienen nosotros desde el 100% de compatibilidad con API.
Loading settings from environment or .jsbeautifyrc (JavaScript-Only)
Además de los argumentos CLI, puede pasar la configuración al ejecutable JS a través de:
- cualquier
jsbeautify_
variable de entorno con prefijo - un
JSON
archivo con formato indicado por el--config
parámetro - un
.jsbeautifyrc
archivo que contieneJSON
datos en cualquier nivel del sistema de archivos anterior$PWD
Las fuentes de configuración proporcionadas anteriormente en esta pila anularán las posteriores.
Setting inheritance and Language-specific overrides
La configuración es un árbol superficial cuyos valores se heredan para todos los idiomas, pero se pueden anular. Esto funciona para la configuración que se pasa directamente a la API en cualquier implementación. En la implementación de Javascript, la configuración se carga desde un archivo de configuración, como .jsbeautifyrc , también puede usar herencia / anulación.
A continuación, se muestra un árbol de configuración de ejemplo que muestra todas las ubicaciones admitidas para los nodos de anulación de idioma. Usaremos indent_size
para analizar cómo se comportaría esta configuración, pero se puede heredar o anular cualquier cantidad de configuraciones:
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
}
}
El uso del ejemplo anterior tendría el siguiente resultado:
- Archivos HTML
- Hereda
indent_size
4 espacios de la configuración de nivel superior. - Los archivos también terminarían con una nueva línea.
- JavaScript y CSS dentro de HTML
- Heredar la
end_with_newline
configuración HTML - Anula su sangría a 2 espacios
- Heredar la
- Hereda
- Archivos CSS
- Reemplace la configuración de nivel superior a un
indent_size
espacio de 1.
- Reemplace la configuración de nivel superior a un
- Archivos JavaScript
- Heredar
indent_size
4 espacios de la configuración de nivel superior - Establecer
preserve-newlines
entrue
- Heredar
CSS & HTML
Además del js-beautify
ejecutable, css-beautify
y html-beautify
también se proporcionan como una interfaz fácil en esos scripts. Alternativamente,
js-beautify --css
o js-beautify --html
lograrán lo mismo, respectivamente.
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.
Los embellecedores CSS y HTML tienen un alcance mucho más simple y poseen muchas menos opciones.
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
27CSS 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
Directivas para ignorar o preservar secciones (solo Javascript)
Embellecedor para las directivas de soporte en los comentarios dentro del archivo. Esto le permite decirle al embellecedor que conserve el formato o ignore por completo parte de un archivo. La entrada de ejemplo a continuación permanecerá modificada después del embellecimiento
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 */
Licencia
Usted es libre de usar esto de la manera que desee, en caso de que lo encuentre útil o funcione para usted, pero debe conservar el aviso de derechos de autor y la licencia. (MIT)
Créditos
- Creado por Einar Lielmanis, einar@jsbeautifier.org
- La versión de Python floreció por Stefano Sanfilippo a.little.coder@gmail.com
- Línea de comandos para node.js por Daniel Stockman daniel.stockman@gmail.com
- Mantenido y ampliado por Liam Newman bitwiseman@gmail.com
Gracias también a Jason Diamond, Patrick Hof, Nochum Sossonko, Andreas Schneider, Dave Vasilevsky, Vital Batmanov, Ron Baldwin, Gabriel Harrison, Chris J. Shull, Mathias Bynens, Vittorio Gambaletta y otros.
(README.md: js-beautify@1.7.5 )