VSCode与Prettier代码格式化工具的使用
  TEZNKK3IfmPf 2023年11月14日 50 0

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

Prettier is an opinionated code formatter

文档:https://www.ctyun.cn/portal/link.html?target=https%3A%2F%2Fprettier.io%2F

属性配置:https://www.ctyun.cn/portal/link.html?target=https%3A%2F%2Fprettier.io%2Fdocs/en/options.html

npm install

示例

// 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

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   34   0   0 python开发语言
TEZNKK3IfmPf