22

Is there any way to run ng lint while watching for file changes during ng serve? To encourage best practices according to the Angular 2 Style Guide our CI tool runs ng lint during the build process and it isn't always a developers first thought to run lint before submitting a pull request.

Is it possible to customize what ng serve does or has anyone figured out a way to include running lint as part of the recompilation process? If not, I'd also be interested in knowing whether others have any opinions on whether this is a good idea or not and why.

Brian Anderson
  • 307
  • 3
  • 11
  • No, currently, there is no such an option. However, tslint is integrated into many popular IDE and Editors. You can maybe update the script tag in package.json to run parallel tasks (npm run start - in script tag you have "start":"ng serve && ng lint" -> in this case linting is automatically started during startup) – Alexander Peinsipp Apr 03 '18 at 13:08
  • There is a work-around, see my answer below. You just need to run both `ng serve` and `npm run lint:watch` in different terminals. – Markus Ende Apr 13 '18 at 13:06

1 Answers1

16

You can define an additional npm script with a watch using nodemon for this.

  1. Install nodemon npm package globally (npm i -g nodemon) or in your project (npm i --save-dev nodemon)
  2. Define the npm script in package.json (under "scripts"): `

    "lint:watch": "nodemon --exec \"npm run lint || exit 1\" --ext ts,html,scss"

  3. Run npm run lint:watch

You can change the --ext ts,html,scss,json to whatever file extensions you want to cause lint to restart. For further documentation of nodemon, see https://github.com/remy/nodemon#nodemon

Markus Ende
  • 830
  • 1
  • 9
  • 21
  • 2
    Edited: you need to add "`|| exit 1`" to the end of the script given in `--exec` because npm will return exit code 2 on lint errors which breaks nodemon's watch. – Markus Ende Apr 13 '18 at 12:17