简体   繁体   English

保持开发者之间的JS格式代码一致?

[英]Keep JS format code consistent between developers?

We keep having problem with Javascript developers are using different code format on the Editors.我们一直遇到 JavaScript 开发人员在编辑器上使用不同代码格式的问题。 Some developers use VSCode, Sublime or PHPStorm.一些开发人员使用 VSCode、Sublime 或 PHPStorm。 We are getting inconsistent code formatting when the developers create a PR (Github).当开发人员创建 PR (Github) 时,我们会遇到不一致的代码格式。

Is there a way a developer can run a command (npm format) which will format the code automatically.有没有一种方法可以让开发人员运行一个命令(npm 格式)来自动格式化代码。 And also CI will do code format check?还有 CI 会做代码格式检查吗?

If you're just looking for a code formatter, Prettier is a great option.如果您只是在寻找代码格式化程序, Prettier是一个不错的选择。 Using Prettier, you can have a central configuration (eg, 4 spaced tabs, double quotes, etc.), and running a single command will clean your files.使用 Prettier,您可以拥有一个中央配置(例如,4 个间隔的制表符、双引号等),并且运行单个命令将清理您的文件。

You can extend this with Husky , which is my go-to choice for git hooks.您可以使用Husky扩展它,这是我对 git hooks 的首选。 Then, you can set up a pre-commit hook which will automatically clean your files using Prettier before committing any new code.然后,您可以设置一个预提交挂钩,它会在提交任何新代码之前使用 Prettier 自动清理您的文件。

You can add the following to your package.json after adding Prettier and Husky as devDependencies :在将devDependencies和 Husky 添加为devDependencies后,您可以将以下内容添加到package.json

{
  "scripts": {
    "prettier-format": "prettier --write 'src/**/*.js'"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run prettier-format"
    }
  }
}

You can also use Onchange, which can be configured to run Prettier after saving any file changes: https://prettier.io/docs/en/watching-files.html您还可以使用 Onchange,它可以配置为在保存任何文件更改后运行 Prettier: https ://prettier.io/docs/en/watching-files.html

You can try Nx , it handles for you Prettier, TSLint and many many other stuff.你可以试试Nx ,它为你处理 Prettier、TSLint 和许多其他的东西。 Then you can run nx format:check (it can be also embedded in a pipeline easily by running npm run format:check ) to check your formatting.然后你可以运行nx format:check (它也可以通过运行npm run format:check轻松嵌入到管道中)来检查你的格式。 nx format:write / npm run format:write will write the rules for you. nx format:write / npm run format:write将为您编写规则。 Works really good in combination with VSCode option Editor: Format on Save turned on , highly recommending.工程在VSCode选项编辑器组合确实不错:在保存格式打开,高度推荐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM