目次
スポンサードリンク
事前準備
以下の記事の内容が完了している前提で本記事を記載しています。
まだの方は、以下から進めてください。
React(TypeScript)プロジェクトの作成方法(Docker、ESLint、Prettier、WebPack)【2/4】 - Reigle 技術ブログ
Prettier
npm install --save-dev prettier eslint-config-prettier
ESLintの設定修正
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
'prettier',
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"react",
"react-hooks",
"@typescript-eslint"
],
"rules": {
},
"overrides": [
{
"files": ["**/*.tsx"],
"rules": {
"react/prop-types": "off"
}
}
],
"settings": {
"react": {
"version": "detect"
},
},
// eslintの対象外ファイル
"ignorePatterns": [
"**/public/*",
"**/node_modules/*",
"**/.vscode/*",
".eslintrc.js",
".prettierrc.js",
],
}
スポンサードリンク
コマンドでPrettierの整形を行う
以下のコマンドを実行する事で、「src」ディレクトリ配下の全てのファイルをPrettierで整形できる。
./node_modules/.bin/prettier --write src/*
VSCodeでPrettierを実行する
VSCode の拡張機能の「Prettier - Code formatter」をインストールする
VSCodeで「command + ,」のショートカットを実行し、「format on save」を検索する。
検索された項目の「Editor: format on save」にチェックを入れる。

「.vscode/settings.json」の内容を以下の様に修正する。
{
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[graphql]": {
"editor.formatOnSave": true
},
"[javascript]": {
"editor.formatOnSave": true
},
"[javascriptreact]": {
"editor.formatOnSave": true
},
"[json]": {
"editor.formatOnSave": true
},
"[typescript]": {
"editor.formatOnSave": true
},
"[typescriptreact]": {
"editor.formatOnSave": true
}
}
これで、ファイル保存時にPrettierが起動し、フォーマットされる様になります。
スポンサードリンク
Prettierのルール設定
プロジェクトのルートに「.prettierrc.js」を作成し、内容に以下を記載する。
※内容はサンプルなので、必要な設定を定義すること。
module.exports = {
trailingComma: "all",
tabWidth: 2,
endOfLine: "auto",
singleQuote: true,
};
Prettierの除外ファイル
プロジェクトのルートに「.prettierignore」を作成し、内容に以下を記載する。
※内容はサンプルなので、必要な設定を定義すること。
# Ignore artifacts: build **/public/* **/node_modules/* **/.vscode/* .eslintrc.js .prettierrc.js **/*.md
本記事の全ての内容(VSCodeの設定など)を含んだソースコードは以下のGitHubにアップしています。
スポンサードリンク
続きは以下の記事です。
React(TypeScript)プロジェクトの作成方法(Docker、ESLint、Prettier、WebPack)【4/4】 - Reigle 技術ブログ