您当前的位置: 首页 >  vscode

彭世瑜

暂无认证

  • 5浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

VSCode与Prettier代码格式化工具的使用

彭世瑜 发布时间:2022-07-16 11:05:40 ,浏览量:5

在这里插入图片描述

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 or .prettierrc.js
module.exports = {
  // 在对象或数组最后一个元素后面加逗号
  trailingComma: 'es5',
  // 空格形式缩进2空格
  tabWidth: 2,
  // 结尾不用分号
  semi: false,
  // 使用单引号
  singleQuote: true,
  // html中单属性换行
  singleAttributePerLine: true,
};

再次格式化

$ 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

VS Code中安装插件Prettier - Code formatter

也可以使用目录中的配置文件

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0561s