Prettier batch formatting and other commands

foreword

Sometimes it is necessary to format files in batches. At present, prettier is the most widely used. This article records some usage commands

1. Install prettier globally

npm install --global prettier

2. Configure .prettierrc.js

Create a configuration file in the project root directory .prettierrc.jsand fill in the configuration as required

module.exports = {
    
    
  overrides: [
    {
    
    
      files: ['*.nvue'],
      options: {
    
    
        parser: 'vue',
      },
    },
  ],
  // 末尾不需要逗号 'es5' none
  trailingComma: 'es5',
  // 大括号内的首尾需要空格
  bracketSpacing: true,
  // 行尾需要有分号
  semi: false,
  // 使用单引号
  singleQuote: true,
  // 一行最多 100 字符
  printWidth: 150,
  // 不使用缩进符,而使用空格
  //useTabs: false,
  // 使用 2 个空格缩进
  //tabWidth: 2,
  //tabSize: 2,
  // 对象的 key 仅在必要时用引号
  //quoteProps: 'as-needed',
  // jsx 不使用单引号,而使用双引号
  //jsxSingleQuote: false,
  // jsx 标签的反尖括号需要换行
  //jsxBracketSameLine: false,
  // 箭头函数,只有一个参数的时候,也需要括号
  //arrowParens: 'always',
  // 每个文件格式化的范围是文件的全部内容
  //rangeStart: 0,
  //rangeEnd: Infinity,
  // 不需要写文件开头的 @prettier
  //requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  //insertPragma: false,
  // 使用默认的折行标准
  //proseWrap: 'preserve',
  // 根据显示样式决定 html 要不要折行
  //htmlWhitespaceSensitivity: 'css',
  // 换行符使用 lf 结尾是 \n \r \n\r auto
  //endOfLine: 'lf',
}

3. Commonly used commands

--config .prettierrc.jsIt means to use the configuration of .prettierrc.js to format the file,
--writewhich means to write permission

3.1 Formatting a single file

prettier --config .prettierrc.js --write ./a/b.js

3.2 Format a certain type of file in a certain folder

prettier --config .prettierrc.js --write ./a/*.js

3.2 Format a certain type of file under multiple folders

prettier --config .prettierrc.js --write ./a/*.js' './b/*.css

3.3 Formatting certain types of files

prettier --config .prettierrc.js --write ./**/**/*.js

3.4 Formatting multiple types of files

prettier --config .prettierrc.js --write ./**/**/*.{js,css,vue}

4. Solve the problem that the file cannot be found

Try adding single quotes to the file address, for exampleprettier --config .prettierrc.js --write './a/b.js'

5. Solve the problem of No parser could be inferred for file

The role in the .prettierrc.js configuration overridesis to specify that class A files use class B files as parsers. If you encounter a No parser could be inferred for file prompt, you can use overrides to solve it:

  overrides: [
    {
    
    
      files: ['*.nvue'],
      options: {
    
    
        parser: 'vue',
      },
    },
  ],

For example, the above example means that all nvue files are formatted using the vue analyzer

Guess you like

Origin blog.csdn.net/iamlujingtao/article/details/119189335