[prettier]代码格式化

主要是实现代码格式化,最好在不同的编辑器中遵守相同的格式化规则

编辑器保存时自动格式化

在VSCODE中实现保存时自动格式化

方式1

文件=>首选项=>设置
[prettier]代码格式化_第1张图片

方式2

通过vscode文件打开的项目中,存在.vscode 文件夹,可以在setting.json设置当前项目的编辑器
在这里插入图片描述

"editor.formatOnSave": true

项目格式化设置

prettier 可选设置

参考官网

"prettier.printWidth": 100, // 超过最大值换行
"prettier.tabWidth": 4, // 缩进字节数
"prettier.useTabs": false, // 缩进不使用 tab,使用空格
"prettier.semi": true, // 句尾添加分号
"prettier.singleQuote": true, // 使用单引号代替双引号
"prettier.proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如 GitHub comment)而按照 markdown 文本样式进行折行
"prettier.arrowParens": "avoid", // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
"prettier.bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
"prettier.disableLanguages": ["vue"], // 不格式化 vue 文件,vue 文件的格式化单独设置
"prettier.endOfLine": "auto", // 结尾是 \n \r \n\r auto
"prettier.eslintIntegration": false, //不让 prettier 使用 eslint 的代码格式进行校验
"prettier.htmlWhitespaceSensitivity": "ignore",
"prettier.ignorePath": ".prettierignore", // 不使用 prettier 格式化的文件填写在项目的.prettierignore 文件中
"prettier.jsxBracketSameLine": false, // 在 jsx 中把'>' 是否单独放一行
"prettier.jsxSingleQuote": false, // 在 jsx 中使用单引号代替双引号
"prettier.parser": "babylon", // 格式化的解析器,默认是 babylon
"prettier.requireConfig": false, // Require a 'prettierconfig' to format prettier
"prettier.stylelintIntegration": false, //不让 prettier 使用 stylelint 的代码格式进行校验
"prettier.trailingComma": "es5", // 在对象或数组最后一个元素后面是否加逗号(在 ES5 中加尾逗号)
"prettier.tslintIntegration": false // 不让 prettier 使用 tslint 的代码格式进行校验

prettier 之 schema 说明文档

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "definitions": {
    "optionsDefinition": {
      "type": "object",
      "properties": {
        "arrowParens": {
          "description": "Include parentheses around a sole arrow function parameter.",
          "default": "always",
          "oneOf": [
            {
              "enum": ["always"],
              "description": "Always include parens. Example: `(x) => x`"
            },
            {
              "enum": ["avoid"],
              "description": "Omit parens when possible. Example: `x => x`"
            }
          ]
        },
        "bracketSameLine": {
          "description": "Put > of opening tags on the last line instead of on a new line.",
          "default": false,
          "type": "boolean"
        },
        "bracketSpacing": {
          "description": "Print spaces between brackets.",
          "default": true,
          "type": "boolean"
        },
        "cursorOffset": {
          "description": "Print (to stderr) where a cursor at the given position would move to after formatting.\nThis option cannot be used with --range-start and --range-end.",
          "default": -1,
          "type": "integer"
        },
        "editorconfig": {
          "description": "Whether parse the .editorconfig file in your project and convert its properties to the corresponding Prettier configuration. This configuration will be overridden by .prettierrc, etc.",
          "default": false,
          "type": "boolean"
        },
        "embeddedLanguageFormatting": {
          "description": "Control how Prettier formats quoted code embedded in the file.",
          "default": "auto",
          "oneOf": [
            {
              "enum": ["auto"],
              "description": "Format embedded code if Prettier can automatically identify it."
            },
            {
              "enum": ["off"],
              "description": "Never automatically format embedded code."
            }
          ]
        },
        "endOfLine": {
          "description": "Which end of line characters to apply.",
          "default": "lf",
          "oneOf": [
            {
              "enum": ["lf"],
              "description": "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
            },
            {
              "enum": ["crlf"],
              "description": "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
            },
            {
              "enum": ["cr"],
              "description": "Carriage Return character only (\\r), used very rarely"
            },
            {
              "enum": ["auto"],
              "description": "Maintain existing\n(mixed values within one file are normalised by looking at what's used after the first line)"
            }
          ]
        },
        "filepath": {
          "description": "Specify the input filepath. This will be used to do parser inference.",
          "type": "string"
        },
        "htmlWhitespaceSensitivity": {
          "description": "How to handle whitespaces in HTML.",
          "default": "css",
          "oneOf": [
            {
              "enum": ["css"],
              "description": "Respect the default value of CSS display property."
            },
            {
              "enum": ["strict"],
              "description": "Whitespaces are considered sensitive."
            },
            {
              "enum": ["ignore"],
              "description": "Whitespaces are considered insensitive."
            }
          ]
        },
        "insertPragma": {
          "description": "Insert @format pragma into file's first docblock comment.",
          "default": false,
          "type": "boolean"
        },
        "jsxSingleQuote": {
          "description": "Use single quotes in JSX.",
          "default": false,
          "type": "boolean"
        },
        "parser": {
          "description": "Which parser to use.",
          "anyOf": [
            {
              "enum": ["flow"],
              "description": "Flow"
            },
            {
              "enum": ["babel"],
              "description": "JavaScript"
            },
            {
              "enum": ["babel-flow"],
              "description": "Flow"
            },
            {
              "enum": ["babel-ts"],
              "description": "TypeScript"
            },
            {
              "enum": ["typescript"],
              "description": "TypeScript"
            },
            {
              "enum": ["acorn"],
              "description": "JavaScript"
            },
            {
              "enum": ["espree"],
              "description": "JavaScript"
            },
            {
              "enum": ["meriyah"],
              "description": "JavaScript"
            },
            {
              "enum": ["css"],
              "description": "CSS"
            },
            {
              "enum": ["less"],
              "description": "Less"
            },
            {
              "enum": ["scss"],
              "description": "SCSS"
            },
            {
              "enum": ["json"],
              "description": "JSON"
            },
            {
              "enum": ["json5"],
              "description": "JSON5"
            },
            {
              "enum": ["json-stringify"],
              "description": "JSON.stringify"
            },
            {
              "enum": ["graphql"],
              "description": "GraphQL"
            },
            {
              "enum": ["markdown"],
              "description": "Markdown"
            },
            {
              "enum": ["mdx"],
              "description": "MDX"
            },
            {
              "enum": ["vue"],
              "description": "Vue"
            },
            {
              "enum": ["yaml"],
              "description": "YAML"
            },
            {
              "enum": ["glimmer"],
              "description": "Ember / Handlebars"
            },
            {
              "enum": ["html"],
              "description": "HTML"
            },
            {
              "enum": ["angular"],
              "description": "Angular"
            },
            {
              "enum": ["lwc"],
              "description": "Lightning Web Components"
            },
            {
              "type": "string",
              "description": "Custom parser"
            }
          ]
        },
        "pluginSearchDirs": {
          "description": "Custom directory that contains prettier plugins in node_modules subdirectory.\nOverrides default behavior when plugins are searched relatively to the location of Prettier.\nMultiple values are accepted.",
          "default": [],
          "oneOf": [
            {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            {
              "enum": [false],
              "description": "Disable plugin autoloading."
            }
          ]
        },
        "plugins": {
          "description": "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
          "default": [],
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "printWidth": {
          "description": "The line length where Prettier will try wrap.",
          "default": 80,
          "type": "integer"
        },
        "proseWrap": {
          "description": "How to wrap prose.",
          "default": "preserve",
          "oneOf": [
            {
              "enum": ["always"],
              "description": "Wrap prose if it exceeds the print width."
            },
            {
              "enum": ["never"],
              "description": "Do not wrap prose."
            },
            {
              "enum": ["preserve"],
              "description": "Wrap prose as-is."
            }
          ]
        },
        "quoteProps": {
          "description": "Change when properties in objects are quoted.",
          "default": "as-needed",
          "oneOf": [
            {
              "enum": ["as-needed"],
              "description": "Only add quotes around object properties where required."
            },
            {
              "enum": ["consistent"],
              "description": "If at least one property in an object requires quotes, quote all properties."
            },
            {
              "enum": ["preserve"],
              "description": "Respect the input use of quotes in object properties."
            }
          ]
        },
        "rangeEnd": {
          "description": "Format code ending at a given character offset (exclusive).\nThe range will extend forwards to the end of the selected statement.\nThis option cannot be used with --cursor-offset.",
          "default": null,
          "type": "integer"
        },
        "rangeStart": {
          "description": "Format code starting at a given character offset.\nThe range will extend backwards to the start of the first line containing the selected statement.\nThis option cannot be used with --cursor-offset.",
          "default": 0,
          "type": "integer"
        },
        "requirePragma": {
          "description": "Require either '@prettier' or '@format' to be present in the file's first docblock comment\nin order for it to be formatted.",
          "default": false,
          "type": "boolean"
        },
        "semi": {
          "description": "Print semicolons.",
          "default": true,
          "type": "boolean"
        },
        "singleAttributePerLine": {
          "description": "Enforce single attribute per line in HTML, Vue and JSX.",
          "default": false,
          "type": "boolean"
        },
        "singleQuote": {
          "description": "Use single quotes instead of double quotes.",
          "default": false,
          "type": "boolean"
        },
        "tabWidth": {
          "description": "Number of spaces per indentation level.",
          "default": 2,
          "type": "integer"
        },
        "trailingComma": {
          "description": "Print trailing commas wherever possible when multi-line.",
          "default": "es5",
          "oneOf": [
            {
              "enum": ["es5"],
              "description": "Trailing commas where valid in ES5 (objects, arrays, etc.)"
            },
            {
              "enum": ["none"],
              "description": "No trailing commas."
            },
            {
              "enum": ["all"],
              "description": "Trailing commas wherever possible (including function arguments)."
            }
          ]
        },
        "useTabs": {
          "description": "Indent with tabs instead of spaces.",
          "default": false,
          "type": "boolean"
        },
        "vueIndentScriptAndStyle": {
          "description": "Indent script and style tags in Vue files.",
          "default": false,
          "type": "boolean"
        }
      }
    },
    "overridesDefinition": {
      "type": "object",
      "properties": {
        "overrides": {
          "type": "array",
          "description": "Provide a list of patterns to override prettier configuration.",
          "items": {
            "type": "object",
            "required": ["files"],
            "properties": {
              "files": {
                "description": "Include these files in this override.",
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                ]
              },
              "excludeFiles": {
                "description": "Exclude these files from this override.",
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                ]
              },
              "options": {
                "type": "object",
                "description": "The options to apply for this override.",
                "$ref": "#/definitions/optionsDefinition"
              }
            },
            "additionalProperties": false
          }
        }
      }
    }
  },
  "id": "https://json.schemastore.org/prettierrc.json",
  "oneOf": [
    {
      "type": "object",
      "allOf": [
        {
          "$ref": "#/definitions/optionsDefinition"
        },
        {
          "$ref": "#/definitions/overridesDefinition"
        }
      ]
    },
    {
      "type": "string"
    }
  ],
  "title": "Schema for .prettierrc"
}

.prettierrc.json 文件设置

位于项目根目录下

{
"semi":false,//使用分号
"singleQuote":true,//单引号
"bracketSpacing":true,//对象中的空格
"tabWidth": 4, // tab 缩进大小
"jsxBracketSameLine": false,// >闭合位置是否换行 true 不换行 false 换行
"bracketSameLine": false,
"editorconfig":true,//启用editorconfig文件设置
# 每行单个属性
# 在 HTML、Vue 和 JSX 中每行强制执行单个属性。
# false- 不要每行强制执行单个属性。
# true- 每行强制执行单个属性。
"singleAttributePerLine": false
}

.editorconfig 文件设置

位于项目根目录下,默认设置

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

两个文件同时存在时,.prettierrc.json 会覆盖.editorconfig 文件内容

你可能感兴趣的:(前端模块开发,格式工厂)