# Sublime

首先确保已经安装了 Prettier 的 npm 包

  1. ctrl/cmd + shift + p 输入 Install Package,输入 JsPrettier 找到包并安装
  2. 可以自定义快捷键,以按需格式化代码

Preferences > Key Binding 的 User Keymap 中,写入如下命令

 {"keys": ["command+alt+f"], "command": "js_prettier" }
1
  1. 更推荐的方式是通过如下配置实现统一的 JS 编码规范 Sublime Text > Preferences > Package Settings > JsPrettier > Settings - User
{
  "debug": false,
  "prettier_cli_path": "",
  "node_path": "",
  "auto_format_on_save": false,
  "auto_format_on_save_excludes": [],
  "auto_format_on_save_requires_prettier_config": false,
  "allow_inline_formatting": false,
  "custom_file_extensions": [],
  "max_file_size_limit": -1,
  "additional_cli_args": {},
  "prettier_options": {
    "printWidth": 80,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true,
    "jsxBracketSameLine": false,
    "parser": "babylon",
    "semi": false,
    "requirePragma": false,
    "proseWrap": "preserve",
    "arrowParens": "avoid"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

prettier_cli_path 是 prettier 的调用地址,可以在命令行用 which prettier 查到

node_path 是 node.js 的地址可以在命令行用 which node 查到

"auto_format_on_save": false 保存时格式化不开,一般手动格式化。

prettier_options.printWidth : 100 每一行的预设宽度设置为100。这个宽度涉及到Prettier判断是否要把一行代码换行。这里设置 100 比较大一些,也可以设置成 80 等。

prettier_options.singleQuote : true 保留单引号,不要把单引号格式化成双引号。

prettier_options.trailingComma : none 对于 json 中最后一个键值对的后面,是否要加逗号(trailing comma)。这里是不要加,设置成 none。但是 Airbnb 的格式规范是最后一行JSON也要加逗号,因为这样把最后一个键值对向上移动多行,也不会造成JSON 的错误,这样代码更健壮。

prettier_options.bracketSpacing : true 括号里面的空间要不要进行格式化,可以选择让 prettier 进行格式化控制,看个人喜好,如果觉得 prettier 不如自己控制好,可以设置为 false。

prettier_options.parser : babylon prettier的编译器一般是两种选择 babylon 或者 flow,这里就用默认的 babylon,babylon的强势就是格式解析。作为另外一个选择 flow,主要是做静态检查会更多。但是 flow 可能存在一些 utf8 字符的 bug (参照prettier parser, difference between babylon and flow #1180),所以尽量使用 babylon。另外这个选项还有 typescript 和 css,当检测到是这两种文件类型是,prettier 会自动从 babylon 切换到 typescript 和 css 来做解析。

Last Updated: 11/2/2020, 2:25:14 PM