利用vscode配置文件 + prettier + eslint实现保存自动格式化

1,103 阅读1分钟

王志远,微医前端技术部

前言

实现保存时自动格式化代码,环境依赖于vscode

2022-05-30 15.48.11.gif

实现步骤

安装插件

  • eslint
  • prettier

实现配置

在项目根路径下创建.vscode文件夹,在其中创建.setting.json文件,这个是项目设置的配置文件,粘贴如下内容;即可以实现对【.vue、tsx、ts】文件的保存自动格式化,如果还需要新增其他的,复制粘贴即可;

mkdir .vscode && cd .vscode && cat > setting.json <<eof
{
  	// 支持.vue文件的格式化
    "[vue]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
     // 匹配.tsx文件
    "[typescriptreact]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
     // 匹配.ts文件
    "[typescript]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "eslint.alwaysShowStatus": true,
    "eslint.format.enable": true,
    "eslint.packageManager": "yarn",
    "eslint.run": "onSave",
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "vetur.validation.template": false,
    "editor.formatOnPaste": true,
    "editor.formatOnType": true,
    "editor.formatOnSave": true,
    "files.eol": "\n"
  }
eof

进阶操作

如果想自定义自己的一些规则,可以在项目根路径下新建.prettierrc文件,内容是一个json对象,举例如下

{
  "semi": false, // 是否分号
  "singleQuote": true, // 是否单引号
  "arrowParens": "always",
  "trailingComma": "all"
}