Kohei Blog

夫・父親・医療系エンジニア

Gatsby+TypeScript+ESLint+Prettier+StyleLintのブログ構築

Gatsbyブログを作ったので、雑に環境構築についてメモしておく。 TypeScriptやReactのキャッチアップも兼ねていたので、ESLintやPrettier、StyleLintも入れてみた。

前回のブログでも書いたが、React+TypeScriptキャッチアップにはもってこいだと思っているので、駆け出しフロントエンドエンジニアの方はぜひ挑戦してほしい。

 

導入手順

  • Gatsbyのセットアップ

  • TypeScriptのインストール

  • ESLintの設定

  • Prettierの設定

  • ESLintとStyleLint設定

  • StyleLintの設定

  • もろもろの設定

Gatsbyのセットアップ

Gatsby公式のQuick Start

 $ npm init gatsby

What would you like to call your site?
✔ · myblog

What would you like to name the folder where your site will be created?
✔ user/ blog

? Will you be using a CMS?
(Single choice) Arrow keys to move, enter to confirm
✔ No (or I'll add it later)
  –
  WordPress
  Contentful
  Sanity
  DatoCMS
  Shopify
  Netlify CMS

? Would you like to install a styling system?
(Single choice) Arrow keys to move, enter to confirm
 No (or I'll add it later)
  –
  Sass
  styled-components
✔ Emotion
  PostCSS
  Theme UI

? Would you like to install additional features with other plugins?
(Multiple choice) Use arrow keys to move, enter to select, and choose "Done" to confirm your choices
 ◯ Build and host for free on Gatsby Cloud
❯◉ Add responsive images
 ◉ Add the Google Analytics tracking script
 ◉ Add page meta tags with React Helmet
 ◉ Add an automatic sitemap
 ◉ Generate a manifest file
 ◉ Add Markdown support (without MDX)
 ◉ Add Markdown and MDX support

今回はCMSは使用せずMarkdownベタ書きします。 CSSフレームワークemotionを選択しました。

npm run develop

TypeScriptのインストール

GatsbyにはTypeScriptが統合されていて、すでに使用できる状態です。 型チェックをするためにはTypeScriptをインストールする必要があります。

GatsbyでTypeScriptを拡張するためのプラグイン gatsby-plugin-typescript もインストールする

$ yarn add -D typescript gatsby-plugin-typescript

ESLintの設定

$ yarn add -D eslint eslint-loader

eslint --initして設定ファイルを作成する

$ yarn run eslint --init

? How would you like to use ESLint? (Use arrow keys)
  To check syntax only
> To check syntax and find problems
  To check syntax, find problems, and enforce code style

? What type of modules does your project use? (Use arrow keys)
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

? Which framework does your project use? (Use arrow keys)
> React
  Vue.js
  None of these

? Does your project use TypeScript? (y/N) y

? Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Browser
 ( ) Node

? What format do you want your config file to be in?
  JavaScript
  YAML
> JSON

The config that you've selected requires the following dependencies:

eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
? Would you like to install them now with npm? (Y/n) y

.eslintrc.json

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/eslint-recommended"
    ],
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

ESLintのルールセット・プラグインの導入

eslint-config-airbnb とその依存関係をインストール

$ yarn add -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks

typescript-eslint をインストール

$ yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

gatsby-plugin-eslint のインストール

$ yarn add -D gatsby-plugin-eslint

上記全部まとめてインストール

yarn add -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks @typescript-eslint/eslint-plugin @typescript-eslint/parser gatsby-plugin-eslint

gatsby-config.js にeslintの設定を追加

plugins: [
    /*

      ...省略

    */
{
      resolve: 'gatsby-plugin-eslint',
      options: {
        // Gatsby required rules directory
        // Default settings that may be ommitted or customized
        stages: ['develop'],
        extensions: ['js', 'jsx', 'ts', 'tsx'],
        exclude: ['node_modules', 'bower_components', '.cache', 'public'],
        // Any additional eslint-webpack-plugin options below
        // ...
      },
    },

]
}

Prettierの設定

$ yarn add -D prettier

.prettier.json

{
  "singleQuote": true,
  "trailingComma": "all",
  "semi": false
}

.prettierignore の編集

.cache/
build/
public/
**/coverage/
**/node_modules/
node_modules/
node_modules
**/*.min.js
*.config.js
.*lintrc.js

ESLintとPrettierの競合を解決

$ yarn add -D eslint-config-prettier

.eslintrc.json

{
  /*

    ...省略

  */
  "extends": [
    "airbnb",
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
		"plugin:@typescript-eslint/recommended-requiring-type-checking",
    "prettier",
    "prettier/@typescript-eslint",
    "prettier/react
  ],
  "parser": "@typescript-eslint/parser",
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [
          ".js",
          ".jsx",
          ".ts",
          ".tsx"
        ]
      }
    }
  },

  /*

    ...省略

  */

  "rules": {
    "no-use-before-define": "off",
    "quotes": [2, "single", { "avoidEscape": true }],
    "react/jsx-filename-extension": [
      "error",
      { "extensions": [".jsx", ".tsx"] }
    ],
    "react/prop-types": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-var-requires": "off",
    "react/no-danger": "off",
    "react/no-unescaped-entities": "off",
    "import/no-extraneous-dependencies": "off",
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ]
  }
}

package.json

"scripts": {
    "develop": "gatsby develop",
    "start": "gatsby develop",
    "build": "gatsby build",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "format:prettier": "prettier --write \\\\"**/*.{js,jsx,ts,tsx,json,md}\\\\"",
    "format:eslint": "eslint --fix \\\\"**/*.{js,jsx,ts,tsx}\\\\"",
    "format": "yarn format:eslint && yarn format:prettier"
  },

参考サイト

StyleLintの設定

どうやら、emotionstylelintにまだ対応していないっぽい。 ただ、 styled-component と同様の設定でも動くらしいので使ってみる。

ただし、FIXオプションは使えないので自動フォーマットは使えない。IDEでのエラーチェックのみ。

styled-components | Stylelint

Gatsbyにはstyled-componentsのプラグインをいれる

$ yarn add -D gatsby-plugin-styled-components

gatsby-config.js

plugins:
`gatsby-plugin-styled-components`,

.stylelintrc.json

{
  "processors": ["stylelint-processor-styled-components"],
  "extends": [
    "stylelint-config-standard",
    "stylelint-config-styled-components",
    "stylelint-prettier/recommended"
  ],
  "rules": {
    "string-quotes": "single"
  }
}

package.json

"scripts: {
...
"stylelint": "stylelint \\\\"**/*.ts\\\\""
}

一応エラーチェックはしてくれた。 ただ、前述したようにFIXオプションは動かないっぽい

参考サイト GatsbyをTypeScript化し、コードの検証と整形をする(ESLint、Prettier、stylelint + styled-components)

もろもろの設定 (参考リンク)

ローカル環境をスマホ実機で確認する

package.json

"develop": "gatsby develop -H 0.0.0.0",