Skip to content

Instantly share code, notes, and snippets.

@underworld14
Last active July 7, 2021 13:27
Show Gist options
  • Save underworld14/d82908d6069b92de3edce852b353275c to your computer and use it in GitHub Desktop.
Save underworld14/d82908d6069b92de3edce852b353275c to your computer and use it in GitHub Desktop.
Setup Eslint and Prettier in Typescript project.

Using ESLint and Prettier in a TypeScript Project

Setup Eslint

yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev

Create eslint configuration file

module.exports = {
  parser: "@typescript-eslint/parser", // Specifies the ESLint parser
  parserOptions: {
    ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
    sourceType: "module" // Allows for the use of imports
  },
  extends: [
    "plugin:@typescript-eslint/recommended" // Uses the recommended rules from the @typescript-eslint/eslint-plugin
  ],
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  }
};

If you using react add the configs.

module.exports = {
  parser: "@typescript-eslint/parser", // Specifies the ESLint parser
  parserOptions: {
    ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
    sourceType: "module", // Allows for the use of imports
    ecmaFeatures: {
      jsx: true // Allows for the parsing of JSX
    }
  },
  settings: {
    react: {
      version: "detetct"
    }
  }
  extends: [
    "plugin:@typescript-eslint/recommended" // Uses the recommended rules from the @typescript-eslint/eslint-plugin
  ],
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  }
};

Adding the prettier to the MIX

yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev
//.eslintrc file

extends: [
  "prettier",
  "plugin:prettier/recommended"
]

Create Prettier rule on .prettierrc

{
  "printWidth": 120,
  "singleQuote": true,
  "trailingComma": "all"
}

Adding script to the package.json

{
  "scripts: {
    "lint": "eslint . --ext .js,.ts,.tsx",
    "lint:fix": "eslint . --ext .js,.ts,.tsx --fix",
    "prettier": "prettier --check '*/**/*.{js,ts,tsx,json}'",
    "prettier:fix": "prettier --write '*/**/*.{js,ts,tsx,json}'"
  }
}

Install Husky & Lint Staged for pre-commit hooks

yarn add [email protected] lint-staged

create husky config file .huskyrc

{
  "hooks": {
    "post-checkout": "yarn",
    "pre-commit": "lint-staged",
    "post-commit": "git status"
  }
}

create lint-staged config file .lintstagedrc

{
  "*.{js,ts,tsx,json}": ["prettier --write", "eslint --fix"]
}
@akimabs
Copy link

akimabs commented Jul 7, 2021

Sangat membantu!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment