46

让你的代码更Prettier!代码风格统一终极方案!

 5 years ago
source link: https://zhuanlan.zhihu.com/p/37478644
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

让你的代码更Prettier!代码风格统一终极方案!

代码不停思考不止

很多团队还在为代码风格头疼。大到采用哪套代码风格方案,小到tab和space之争,都是团队开发面临的选择。之前解决这种代码统一问题的方案是:EditorConfig,或者ESLint

这篇文章介绍Prettier。写这篇文章前我搜了一下知乎,发现竟然还没有人普及Prettier!

Prettier在官网首页最想表达的就是:An opinionated code formatter,has few options...,这是必须在文章开始讲清楚的。

什么是opinionated?就是有态度有倾向,尽量减少配置项!相反的意思是Unopinionated.

开发框架也会分为opinionated和unopinionated。

这些讨论就是:

What is opinionated software?

https://medium.com/@stueccles/the-rise-of-opinionated-software-ca1ba0140d5b

Opinionated vs modular web frameworks

例如在下面这篇文章中就说:

Angular is a full-featured “opinionated” framework.
React and Vue are “non-opinionated” frameworks.

Comparison with React vs Angular vs Vue Frameworks

以我接触过的框架举例来说,

Spring Boot就是opinionated:

v2-2b86d68a963c4f6d349fe281cd1671d4_720w.jpg

注意:need very little Spring configuration。其实就是has few options。这也是Spring Boot区别于传统直接基于Spring Framework开发的区别所在。而同样,opinionated(has few options)也是Prettier和ESLint/EditorConfig所区别的一大特性。

opinionated的另外一个同义词是Convention over configuration,或者coding by convention。

而Express是unopinionated:

Express只给你API,告诉你各种参数,其他都不给,想要更多的功能去找middleware或调用API自己写。

如今很多前端项目都已经默认集成了Prettier,例如create-react-app,vue-cli,angular-cli:

其实Prettier虽功能强大,但是却简单易用,所以大部分内容来自官网的翻译解释。

What is Prettier?
An opinionated code formatter
Supports many languages
Integrates with most editors
Has few options

什么是Prettier?

一个有态度的代码格式化工具

支持多种语言

继承绝大多数编辑器

Why?
You press save and code is formatted
No need to discuss style in code review
Saves you time and energy
And more

为什么用Prettier?

你只需要保存文件,代码就会被整理格式

代码复查的时候不需要再争论风格

节约你的实践和经历

不集成编辑器,只用Prettier的用法:

  1. 把prettier加入到项目:
    yarn add prettier --dev --exact
  2. 用一个文件验证是否成功:
    yarn prettier --write src/index.js
  3. git提交代码的时候自动运行prettier:
    yarn add pretty-quick husky --dev

    然后编辑 package.json:{
    "scripts": {
    "precommit": "pretty-quick --staged"
    }
    }

可集成的编辑器包括:

Atom:prettier/prettier-atom

Visual Studio Code:prettier/prettier-vscode

Sublime Text:JsPrettier - Packages - Package Control

WebStorm、PHPStorm:内置了Prettier,只需要配置就可以。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK