Tutorial

Visual Studio CodeでPrettierを使用してコードをフォーマットする方法

Published on December 16, 2020
日本語
Visual Studio CodeでPrettierを使用してコードをフォーマットする方法

はじめに

コーディングスタイルを整えるのは骨の折れる作業ですが、最新の開発ツールを使用すれば、チームのコードベースの一貫性を自動的に保てます。

この記事では、Prettier をセットアップして、Visual Studio Code(VS Code)のコードを自動でフォーマットします。

デモ用にサンプルコードをフォーマットします。

const name = "James";

const person ={first: name
}

console.log(person);

const sayHelloLinting = (fName) => {
console.log(`Hello linting, ${fName}`)
}

sayHelloLinting('James');

コードフォーマットを見慣れていれば、誤りがいくつかあるのに気付くでしょう。

  • 一重引用符と二重引用符が混在しています。
  • person オブジェクトの1つ目のプロパティは、行内に収める必要があります。
  • 関数内のコンソールステートメントは、インデントする必要があります。
  • アロー関数のパラメータを囲むオプションのカッコが思い通りでないかもしれません。

前提条件

このチュートリアルでは、Visual Studio Code をダウンロードしてインストールします。

Visual Studio Code でPrettier を使用するには、拡張機能をインストールします。これを行うには、VS CodeのExtension panelでPrettier - Code Formatterを検索します。Prettierを初めてインストールする場合、ここで表示されるuninstallボタンの代わりにinstallボタンが表示されます。

Prettier extension readme

ステップ1 — Format Documentコマンドの使用

Prettier拡張機能をインストールしたら、それを利用してコードをフォーマットできます。まず、Format Documentコマンドを試してみましょう。このコマンドは、コードの空白、行の折り返し、引用符を一貫したフォーマットに整えます。

コマンドパレットを開くには、macOS なら**COMMAND + SHIFT + Pキーを、 WindowsならCTRL + SHIFT + P**キー を押します。

コマンドパレットで、formatを検索し、Format Documentを選択します。

Command palette opened with results for format

フォーマットの選択を求められます。Configureボタンをクリックして進みます。

Prompt for selecting a default formatter

次に、Prettier - Code Formatterを選択します。

Selecting Prettier

**注:**default formatterの選択プロンプトが表示されなければ、Settingsにて手動で変更できます。Editor: Default Formatteresbenp.prettier-vscodeに設定します。

コードの書式が、空白、行の折り返し、引用符の整合性に関してフォーマットされました。

const name = 'James';

const person = { first: name };

console.log(person);

const sayHelloLinting = (fname) => {
  console.log(`Hello linting, ${fName}`);
}

sayHelloLinting('James');

CSSファイルでも同様に機能します。インデント、波括弧、改行位置、セミコロンで一貫性に欠箇所が、きれいに整ったコードになります。例えば:

body {color: red;
}
h1 {
  color: purple;
font-size: 24px
}

次のように再フォーマットされます。

body {
  color: red;
}
h1 {
  color: purple;
  font-size: 24px;
}

このコマンドを詳しく見たので、自動で実行するように実装する方法を見てみましょう。

ステップ2 — 保存時にコードをフォーマットする

これまではコードのフォーマットを手動で実行してきました。このプロセスを自動化するには、保存時にファイルを自動でフォーマットする設定をVS Code で選択します。また、これによりコードは、未フォーマットのバージョンコントロールとはみなされなくなります。

この設定を変更するには、macOS ではCOMMAND + (プラス)キー、Windows ではCTRL + (プラス)キーを押して、Settingsメニューを開きます。メニューが開いたら、**Editor: Format On Save**を検索し、そのオプションにチェックが入っていることを確認します。

Editor: Format On Save checked

この設定が完了したら、いつものようにコードを作成すれば、ファイルを保存する際に自動でフォーマットされます。

ステップ3 — Prettierの設定変更

Prettierは、デフォルトで多くのことを行いますが、設定をカスタマイズすることもできます。

Settings メニューを開きます。次に、Prettier を検索します。これにより、変更可能な設定がすべて表示されます。

Configuration Settings for Prettier

最も一般的な設定をいくつか以下に示します。

  • Single Quote - Single QuoteかDouble Quoteを選択します。
  • Semi - 行末にセミコロンを付けるかどうか選択します。
  • Tab Width - Tabスペース1個あたりの半角スペースの数を指定します。

VS Code で組み込み設定メニューを使用するデメリットは、チームの開発者間での一貫性が確保されないことです。

ステップ4 — Prettier設定ファイルを作成する

自分のVS Code を設定変更しても、他の誰かのマシンはまったく異なる設定になっているかもしれません。プロジェクト用の設定ファイルを作成すれば、チーム全体で一貫性のあるフォーマットが確立できます。

次のいずれかの拡張子を持つ.prettierrc.extension という新しいファイルを作成します。

  • yml
  • yaml
  • json
  • js
  • toml

JSONを使用した簡単な設定ファイルの例を以下に示します。

{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}

設定ファイルの詳細については、Prettier Docsを参照してください。このようなファイルを作成し、プロジェクトに取り込むことで、チームメンバー全員が同じフォーマットルールに従って作業できます。

まとめ

コードに一貫性を持たせることは、良いことです。複数のコラボレーターとの共同作業において特に有効です。一連の設定について共通認識を持っておくと、読みやすく理解しやすいコーディングに役立ちます。コードインデントのような些細な問題と格闘する代わりに、やり甲斐のある技術的課題の解決に時間が充てられます。

Prettier は、コードフォーマットに一貫性を与え、そのプロセスを自動化します。

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.