Create React App with TypeScript, Prettier, and ESLint

Mon, 4 Mar 2019

Setup

# Start a new Create React App project that uses TypeScript:
yarn create react-app crats-app --typescript

# Add all the dependencies required for Prettier and ESLint:
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-jest eslint-plugin-prettier eslint-plugin-react prettier

ESLint Config

Remove the ESLint config from the package.json and add a .eslintrc.js file:

module.exports = {
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser to use TS.
  extends: [
    'eslint:recommended', // Standard eslint rules.
    'plugin:react/recommended', // React specific linting rules.
    'plugin:@typescript-eslint/recommended', // Allows for TypeScript-specific linting rules to run.
    'prettier/@typescript-eslint', // Disables ESLint rules that might conflict with prettier.
    'plugin:prettier/recommended', // Runs prettier as an ESLint rule.
  ],
  settings: {
    react: {
      version: 'detect', // Automatically picks the version you have installed.
    },
  },
  env: {
    // Global variables:
    browser: true,
    node: true,
    es6: true,
    'jest/globals': true, // Allows "it", "describe" etc.
  },
  plugins: ['@typescript-eslint', 'react', 'jest'], // provides extra rules.
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features.
    sourceType: 'module', // Allows for the use of imports.
  },
  rules: {
    'prettier/prettier': [
      'error',
      {
        // Your Prettier rules
        proseWrap: 'always',
        semi: false,
        singleQuote: true,
        trailingComma: 'all',
        printWidth: 100,
      },
    ],
    'react/prop-types': 'off', // Disable prop-types as TS is used for type checking.
    '@typescript-eslint/explicit-function-return-type': 'off', // Allows functional components, should be fixed soon: https://github.com/typescript-eslint/typescript-eslint/issues/149
    '@typescript-eslint/explicit-member-accessibility': 'off', // Allows not having to set public/private on class properties.
    'no-var': 'error', // Must use const or let.
  },
}

VSCode Config

{
  "eslint.validate": [
    {
      "language": "javascript",
      "autoFix": true
    },
    {
      "language": "javascriptreact",
      "autoFix": true
    },
    {
      "language": "typescript",
      "autoFix": true
    },
    {
      "language": "typescriptreact",
      "autoFix": true
    }
  ],
  "eslint.autoFixOnSave": true,
  "eslint.options": {
    "rules": {
      "prettier/prettier": "warn" // Locally report Prettier formatting as warnings.
    }
  },
  "prettier.eslintIntegration": true // Use eslintrc's prettier rules when running format.
}

Repo: https://github.com/will-stone/crats-eslint