LoginSignup
12
7

More than 3 years have passed since last update.

Prettierの文字数制限の確認

Last updated at Posted at 2019-07-19

Prettierの--print-widthは上限値だと思ってたのだけど、改行を嫌って極端に大きい数値を設定すると、逆に改行したいときにも纏められる(改行が消える)という学び。

$ npx prettier for_test/test.js --write --print-width=800
-import {
-  CollectionDashboard,
-  DashboardPlaceholder
-} from "../components/collections/collection-dashboard/main";
+import { CollectionDashboard, DashboardPlaceholder } from '../components/collections/collection-dashboard/main';q

ちなみに俺は120以上に設定したことがなかったので、気付かなかった。基本的にはdefaultの80であまり困らない勢。

正直、Prettierに対しては雑に書いたコードが勝手に整形される以上の感想を持ったことがないので、「どうしてもone-linerにしたい」勢のストレスを理解してなかった。是非もないよネ!(レビューしたくないなとは思ったが)

Prettierに仕事をさせない

In prettier, print width is not a rule, it’s actually an input into the algorithm used to print code. Due to this it is impossible to turn off. You can set it to a very high number (not recommended) or use // prettier-ignore comments to disable prettier on a chunk of code.
https://github.com/prettier/prettier/issues/3468

printWidth はPrettierにとって必要な値で、ルールではない。
無効にすることは不可能なので、極端に高い値を指定するか(望まない整形になりやすくなるが)、 // pretteir-ignore を使うべし。gitignore syntax.prettierignoreを置くこともできる。

Ignoreing Code

// prettier-ignore
@@ -17,42 +17,51 @@ import {
 } from "../components/collections/collection-dashboard/main";

 // several lines
-import {
-  CollectionDashboard,
-  DashboardPlaceholder
-} from "../components/collections/collection-dashboard/main";
+import { CollectionDashboard, DashboardPlaceholder } from '../components/collections/collection-dashboard/main';

// prettier-ignore付けると、いい感じに該当箇所だけ無視してくれる(JSの場合、next-lineとかか範囲指定とかしなくても巧くいく風)。

大抵の人は1行が長くなりすぎないように努力するので、大半のコードは80文字以下になる。エッジケースの対応でいちいち設定を変えてるとルールが意味を為さなくなるので、コメントで対応したほうが良いでしょう。極端に長い数値を設定された結果、普通のコードもone-linerになるようになって「Prettierはクソ」て苦情が来たりします。

小技

What Prettier is not concerned aboutにもあるけど、+と引用符で繋げていく系の文字列は整形対象になると細かく切られてしまうので、template literalに換えると良い。

// long html strings
-var quote_and_plus   = '<div id="' + widgetContentID + '" style="' + widgetContentStyles + '">' + '</div>';
+var quote_and_plus =
+     '<div id="' +
+     widgetContentID +
+     '" style="' +
+     widgetContentStyles +
+     '">' +
+     '</div>';
 var template_literal = `<div id="${widgetContentID}" style="${widgetContentStyles}"></div>`;

エディタにエラーを出さない

スクリーンショット 2019-07-19 19.39.29.png

変換されること自体はいいけど、書いてるときにエラー出されると気が散る、て意見もあり。
スクリーンショット 2019-07-19 17.23.26.png

Prettier自体はエラー出さないので、eslint-plugin-prettierとか咬ましてる場合の、ESLintの警告ですね。なんでrules指定すれば制御できます。

     "es6": true
   },
   "rules": {
-    "prettier/prettier": "error"
+    "prettier/prettier": "warn"
   }
 }

スクリーンショット 2019-07-19 17.23.45.png

この記事は Corne Cherry で書きました。

12
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7