Skip to content

Instantly share code, notes, and snippets.

@estorgio
Last active August 11, 2024 22:13
Show Gist options
  • Save estorgio/e8bcaa8e87d0fcdcf85fdf598956e34c to your computer and use it in GitHub Desktop.
Save estorgio/e8bcaa8e87d0fcdcf85fdf598956e34c to your computer and use it in GitHub Desktop.
Setting up Prettier and ESLint with pre-commit hook

Setting up Prettier and ESLint with pre-commit hook

  • Initialize Git repository
    git init
  • Create .gitignore file and add the following:
    node_modules/
    *.env
    
  • Create a package.json file with npm init
    npm init -y
  • Install dev dependencies
    npm i -D prettier eslint husky lint-staged
  • Initialize ESLint config
    npx eslint --init
  • Create .prettierrc file and add the following rules:
    {
      "printWidth": 80,
      "tabWidth": 2,
      "useTabs": false,
      "semi": true,
      "singleQuote": true,
      "quoteProps": "as-needed",
      "jsxSingleQuote": false,
      "trailingComma": "all",
      "bracketSpacing": true,
      "jsxBracketSameLine": true,
      "arrowParens": "avoid",
      "endOfLine": "auto"
    }
  • Open package.json file and add the following sections:
    "husky": {
      "hooks": {
        "pre-commit": "lint-staged"
      }
    },
    "lint-staged": {
      "*.{js,jsx}": [
        "prettier --write",
        "eslint --fix",
        "git add"
      ],
      "*.{html,css,less,ejs}": [
        "prettier --write",
        "git add"
      ]
    }
  • At this point, your pre-commit linting setup should be working and ready for use.

Make your first commit

  • Open .eslintrc.js file and add no-console rule under rules section.
    module.exports = {
      ...
      rules: {
        'no-console': 'off',
      },
    };
  • Add this sample app.js file:
    console.log('one');
    var ww = process.env.NODE_ENV.trim.toLowerCase();
    if (ww === 'production') {
      console.log('Another one');
    } else {
      console.log('test');
    }
  • Commit all files
    git add .
    git commit -m "Initial commit"
  • If all goes well, your app.js should now be formatted properly :
    console.log('one');
    const ww = process.env.NODE_ENV.trim.toLowerCase();
    if (ww === 'production') {
      console.log('Another one');
    } else {
      console.log('test');
    }
@smshaikh-official
Copy link

For someone who is still looking to setup husky with new interface, please checkout this article/blog https://duncanlew.medium.com/getting-started-with-husky-and-lint-staged-for-pre-commit-hooks-c2764d8c9ae

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