Vue项目配置prettier ,快速格式化项目

2022-02-25  本文已影响0人  jw_fc89

话不多说,看代码

先在package.json添加如下脚本

 "scripts": {
    "prettier": "node prettier.js",
    "pretty-quick": "pretty-quick --staged --pattern \"**/*.*(js|vue)\"",
  },
"devDependencies": {
  "pre-commit": "^1.2.2",
  "prettier": "^1.19.1",
  "pretty-quick": "^3.1.0"
}
"pre-commit": [
    "pretty-quick"
 ]

操作完这些就先运行一下yarn安装一下相应依赖包

项目根目录下添加如下文件

这一步大家基本上可以完全copy,按项目需要,需略微修改即可(毕竟也不难)prettier文档

.prettierrc

{
    "arrowParens": "always",
    "bracketSameLine": false,
    "bracketSpacing": true,
    "embeddedLanguageFormatting": "auto",
    "htmlWhitespaceSensitivity": "css",
    "insertPragma": false,
    "jsxSingleQuote": false,
    "printWidth": 120,
    "proseWrap": "preserve",
    "quoteProps": "as-needed",
    "requirePragma": false,
    "semi": true,
    "singleQuote": false,
    "tabWidth": 2,
    "trailingComma": "es5",
    "useTabs": false,
    "vueIndentScriptAndStyle": false
}

prettier.js

const prettier = require("prettier");
const fs = require("fs");
const getPrettierFiles = require("./getPrettierFiles");
const prettierConfigPath = require.resolve("./.prettierrc");
const chalk = require("chalk");

let didError = false;

const files = getPrettierFiles();

files.forEach((file) => {
  const options = prettier.resolveConfig.sync(file, {
    config: prettierConfigPath,
  });
  const fileInfo = prettier.getFileInfo.sync(file);
  if (fileInfo.ignored) {
    return;
  }
  try {
    const input = fs.readFileSync(file, "utf8");
    const withParserOptions = {
      ...options,
      parser: fileInfo.inferredParser,
    };
    const output = prettier.format(input, withParserOptions);
    if (output !== input) {
      fs.writeFileSync(file, output, "utf8");
      console.log(chalk.green(`${file} is prettier`));
    }
  } catch (e) {
    didError = true;
  }
});

if (didError) {
  process.exit(1);
}
console.log(chalk.hex("#1890FF")("prettier success!"));

getPrettierFiles.js

const glob = require("glob");

const getPrettierFiles = () => {
  let files = [];
  const jsFiles = glob.sync("src/**/*.js*", { ignore: ["**/node_modules/**", "build/**"] });
  const tsFiles = glob.sync("src/**/*.ts*", { ignore: ["**/node_modules/**", "build/**"] });
  const configFiles = glob.sync("config/**/*.js*", { ignore: ["**/node_modules/**", "build/**"] });
  const vueFiles = glob.sync("scripts/**/*.vue");
  const lessFiles = glob.sync("src/**/*.less*", { ignore: ["**/node_modules/**", "build/**"] });
  files = files.concat(jsFiles);
  files = files.concat(tsFiles);
  files = files.concat(configFiles);
  files = files.concat(vueFiles);
  files = files.concat(lessFiles);
  if (!files.length) {
    return;
  }
  return files;
};
module.exports = getPrettierFiles;

格式化

配置完以上这些就可以运行yarn prettier命令格式项目代码结构了

上一篇下一篇

猜你喜欢

热点阅读