prettier代码格式化工具的使用

在这里插入图片描述

Prettier is an opinionated code formatter

文档:https://prettier.io/

属性配置:https://prettier.io/docs/en/options.html

npm install --save-dev prettier

示例

// src/index.js
function foo(a,b){
    
    return a+b}

格式化代码文件输出到命令行

$ npx prettier src/index.js

// src/index.js
function foo(a, b) {
    
    
  return a + b;
}

格式化文件并覆盖现有文件

npx prettier --write src/index.js

示例2:

// src/index.js
function foo(a,b){
    
    return a+b}
function func(){
    
    console.log("Hello World");}
$ npx prettier src/index.js

// src/index.js
function foo(a, b) {
    
    
  return a + b;
}
function func() {
    
    
  console.log("Hello World");
}

默认情况下

  • 行首2个空格
  • 句尾分号
  • 变量之间增加空格
  • 使用双引号

使用配置文件

// prettier.config.js
module.exports = {
    
    
    // 结尾逗号风格
    trailingComma: "es5",
    // 行首4个空格
    tabWidth: 4,
    // 不要结尾分号
    semi: false,
    // 使用单引号
    singleQuote: true,
};

再次格式化

扫描二维码关注公众号,回复: 14379002 查看本文章
$ npx prettier src/index.js

// src/index.js
function foo(a, b) {
    
    
    return a + b
}
function func() {
    
    
    console.log('Hello World')
}

还可以配合.editorconfig一起使用

[*]
charset = utf-8
insert_final_newline = true
end_of_line = lf
indent_style = space
indent_size = 2
max_line_length = 80

猜你喜欢

转载自blog.csdn.net/mouday/article/details/125817379