代码美化器

使用说明

本工具使用 js-beautify 库进行代码美化。以下是主要函数的使用说明:

主要函数

函数名 说明 示例
js_beautify(code, options) 美化 JavaScript 代码 js_beautify('var x=1;', {indent_size: 2})
css_beautify(code, options) 美化 CSS 代码 css_beautify('.class{color:red;}', {indent_size: 2})
html_beautify(code, options) 美化 HTML 代码 html_beautify('<div><p>text</p></div>', {indent_size: 2})

常用参数

参数 类型 说明 默认值
indent_size number 缩进空格数 4
indent_char string 缩进字符(空格或制表符) ' '
preserve_newlines boolean 是否保留原有换行 true
max_preserve_newlines number 最大保留连续换行数 10
wrap_line_length number 自动换行的行长度(0 表示不换行) 0
end_with_newline boolean 是否在文件末尾添加换行 false

HTML 专用参数

参数 类型 说明 可选值
wrap_attributes string 属性换行方式 'auto', 'force', 'force-aligned', 'force-expand-multiline', 'aligned-multiple'
indent_scripts string 脚本标签的缩进方式 'normal', 'keep', 'separate'
brace_style string 大括号样式 'collapse', 'expand', 'end-expand', 'none'

CSS 专用参数

参数 类型 说明 默认值
selector_separator_newline boolean 选择器之间是否换行 true
newline_between_rules boolean 规则之间是否换行 true

JavaScript 专用参数

参数 类型 说明 默认值
keep_array_indentation boolean 是否保持数组缩进 false
break_chained_methods boolean 链式方法调用是否换行 false
space_before_conditional boolean 条件语句前是否加空格 true

使用示例

// JavaScript 美化
var options = {
    indent_size: 2,
    preserve_newlines: true,
    max_preserve_newlines: 2,
    end_with_newline: true
};
var beautified = js_beautify('var x=1;var y=2;', options);

// CSS 美化
var cssOptions = {
    indent_size: 2,
    selector_separator_newline: true,
    newline_between_rules: true
};
var beautified = css_beautify('.class{color:red;}', cssOptions);

// HTML 美化
var htmlOptions = {
    indent_size: 2,
    wrap_attributes: 'auto',
    indent_scripts: 'separate'
};
var beautified = html_beautify('<div><p>text</p></div>', htmlOptions);

更多信息

更多详细参数和选项,请参考 js-beautify 官方文档