LoginSignup
3
6

More than 3 years have passed since last update.

Prettier 入門

Last updated at Posted at 2019-03-12

スクリーンショット 2019-03-10 12.44.19.png

Prettier とは

  • Prettier · Opinionated Code Formatter
  • コードフォーマッタ (コード整形ツール)
  • HTML, CSS, JavaScript, Markdown, YAML, GraphQLなどの言語に対応している (詳しくは公式サイト参照)
  • Atom, Emacs, Espresso, Sublime Text, Vim, Visual Studio, VS Code, WebStorm などのエディタでプラグインが提供されている(もちろんnodeのモジュールとして単体でも使える)

コードフォーマッタとは

以下のように、指定したルールに沿って、ソースコードを自動整形するツール。

  • HTML
<!-- 整形前 -->
<!DOCTYPE html>
<html lang="ja">
  <head>
  <meta charset="UTF-8" />
      <meta name="viewport"   content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>Sample</title>
  </head>
    <body>
        Sample
  </body>

</html>


<!-- 整形後 -->
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Sample</title>
  </head>
  <body>
    Sample
  </body>
</html>
  • CSS
/* 整形前 */
.hogehoge {
    background-color: #fff;
  color: #000;
}
.hogehoge::before {
    content: "";
  }


/* 整形後 */
.hogehoge {
  background-color: #fff;
  color: #000;
}
.hogehoge::before {
  content: '';
}
  • JavaScript
// 整形前
const increment = x=>x++;


// 整形後
const increment = (x) => x++;

とりあえず使ってみる

$ npm init -y
$ npm install --save-dev --save-exact prettier
$ npx prettier --write src/**/*.*

設定を変更する

詳細な設定値の意味については、公式サイト参照

.prettierrc.js
module.exports = {
  // デフォルト設定
  // printWidth: 80
  // tabWidth: 2,
  // useTabs: false,
  // semi: ture,
  // singleQuote: false,
  // quoteProps: 'as-needed',
  // jsxSingleQuote: false,
  // trailingComma: 'es5',
  // bracketSpacing: true,
  // jsxBracketSameLine: false,
  // arrowParens: 'always',
  // rangeStart: 0,
  // rangeEnd: Infinity,
  // jsxBracketSameLine: false,
  // requirePragma: false,
  // insertPragma: false,
  // proseWrap: 'preserve',
  // htmlWhitespaceSensitivity: "css",
  // vueIndentScriptAndStyle: false,
  // endOfLine: 'lf',
  // embeddedLanguageFormatting: 'auto',
  // 特定のファイルのみ設定をオーバーライドする
  overrides: [
    // HTMLファイル
    {
      files: '*.html',
      options: {}
    },
    // CSSファイル
    {
      files: '*.css',
      options: {}
    },
    // jsファイル
    {
      files: '*.js',
      options: {
        trailingComma: 'es5',
        arrowParens: 'always',
        singleQuote: true
      }
    }
  ]
};

ファイル保存時に自動フォーマットしたい

他のモジュールと組み合わせれば可能。

$ npm install --save-dev onchange
$ npx onchange "src/**/*.*" -- prettier --write {{changed}}

サンプルコード

おすすめ設定

Prettierのおすすめ設定

3
6
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
3
6