Prettier学习笔记

279 阅读3分钟

概述

Prettier 在整个代码库中强制使用一致的代码样式(代码样式不会影响 AST),因为它丢弃了原始样式,并将代码进行解析,并按照自己的规则重新打印出已解析的 AST,并且而该规则将行的最大长度也考虑在内,必要时会将代码折行。使用Prettier可以帮助我们公司内部代码风格的统一。

使用

安装

npm install --save-dev --save-exact prettier

忽略文件配置

配置.prettierignore,与git的gitignore配置相似,也可以在行内使用// prettier-ignore

(使用了prettier --wirte的index.ts文件)

(使用了忽略配置的代码片段)

可以看到在函数参数上的区别,在类型定义上,使用prettier的代码会在:之后加上空格

使用方法

可以使用以下命令执行

prettier [options] [file/dir/glob ...]

为了格式化文件,可以加上--write(这样会重写文件哦)

例子:

class TreeNode {
  val: number
  left: TreeNode | null
  right: TreeNode | null
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
      this.val = (val===undefined ? 0 : val)
      this.left = (left===undefined ? null : left)
     this.right = (right===undefined ? null : right)
 }
}

function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
    if(root ===null)return false;
    if(root.left ===null&&root.right ===null){
        return targetSum ===root.val;
    }
    return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
};

执行命令prettier --wirte 文件名后

class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
  if (root === null) return false;
  if (root.left === null && root.right === null) {
    return targetSum === root.val;
  }
  return (
    hasPathSum(root.left, targetSum - root.val) ||
    hasPathSum(root.right, targetSum - root.val)
  );
}

可以看到代码格式变得十分好看

如果你想对你格式化后的文件进行检查的话,你可以执行以下命令

prettier --check 文件

现在故意将格式进行修改,再执行一次检查

可以看出报warning

如果反复使用更漂亮的文件格式化,则当 Prettier 尝试查找配置文件时,您将产生较小的性能成本。为了跳过此,您可以要求 Prettier 找到配置文件一次,并在以后反复使用它,使用以下命令

prettier --find-config-path 文件

运行:

执行格式化

prettier --config 配置位置 --write 需要格式化的文件

基础用法

prettier --config ./.prettierrc --write ./index.js

扩展用法(自定义文件配置以及格式化vue文件)

prettier --config ./pre.js --write ./index.vue

配置Prettier

设置print-width,即在一行显示的字符个数

在CLI中,使用--print-width 选项

在配置文件中,可以使用printWidth: 选项

设置Tab-width,规定tab的空格数量(Prettier默认为2)

在CLI中,使用--tab-width 选项

在配置文件中,可以使用tabWidth: 选项

设置分号,规定是否在代码块后有分号(默认有)

在CLI中,使用--no-semi

在配置文件中,使用semi:

设置单引号还是双引号(默认为false)

在CLI中,使用--single-quote

在配置文件中,使用singleQuote:

设置对象的键值对前后空格

例如:

  • true - Example: { foo: bar }.

  • false - Example: {foo: bar}.

在CLI中,使用--no-bracket-spacing

在配置文件中,使用bracketSpacing:

设置箭头函数是否单个参数不要括号

"always" - Always include parens. Example: (x) => x

"avoid" - Omit parens when possible. Example: x => x

在CLI中,使用--arrow-parens <always|avoid>

在配置文件中,使用arrowParens: "<always|avoid>"

体会

感觉prettier还是不难用的,可以使代码拥有更好的可读性,以后多多实践