1
0

More than 1 year has passed since last update.

ESLintのavoidEscapeを使って、引用符(')を含む文字列のクォーテーションがPrettierに勝手に「"」にされても許可するようにする

Posted at

タイトルがすごく分かりにくいですが、つまりこういうことです↓

こんな文字列があったとします。

"Enter your email address below and we'll send you a link to reset your password."

we'llはアポストロフィとしてシングルクォーテーションが使われてますね。

prettierの下記の設定により、自動的にシングルクォーテーションに置き換えられ…ません!

{
  "singleQuote": true,
    // 他の設定
}

というのも、prettierが処理をするプロセスには以下の仕様があるようです。

FYI, this is how Prettier handles quotes:

  1. JSX always uses double quotes.
  2. The quote that results in the least number of escapes is chosen.
  3. Finally, the singleQuote option is used to choose quote.
    https://github.com/prettier/prettier/issues/2338#issuecomment-311776517

つまり、本例は、エスケープすべき「'」があるので、最もエスケープが少ない処理(エスケープ回数0)がされた結果となります。

無理やり(?)シングルクォーテーションを使うと、エスケープ\'が1回使われます。これを回避した形になります。

'Enter your email address below and we\'ll'

ESLintと競合してしまう

Prettierにより、例外的にダブルクォーテーションが使われる理由がわかりましたが、今度はESLintの次のルールに違反します。

.eslintrc.js
~~~省略~~~
quotes: ['error', 'single'],
~~~省略~~~

スクリーンショット 2023-05-08 0.34.11.png

avoidEscapeで解決

下記Issueで解決されていますが、
avoidEscapeオプションを指定してあげることで、ESLintが文字列内にシングルクォーテーションが使われているときは無視することができます。

"avoidEscape": true allows strings to use single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise

.eslintrc.js
~~~省略~~~
quotes: ['error', 'single', { avoidEscape: true }],
~~~省略~~~

1
0
0

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
1
0