Blog>
Snippets

Automating Linting and Formatting

Use Angular CLI to run lint checks and auto-format code using TSLint and Prettier to ensure code quality.
// 1. Install TSLint and Prettier as dev dependencies
npm install --save-dev tslint prettier
Install TSLint and Prettier as development dependencies using npm. These will be used for linting and code formatting.
// 2. Initialize TSLint configuration
./node_modules/.bin/tslint --init
Initialize TSLint by creating a tslint.json configuration file in your project root.
// 3. Create a .prettierrc file for Prettier configurations
// .prettierrc
{
  "singleQuote": true,
  "semi": false
}
Create a Prettier configuration file (.prettierrc) to customize code formatting rules.
// 4. Update package.json to include linting and formatting scripts
// package.json
"scripts": {
  "lint": "ng lint",
  "format": "prettier --write 'src/**/*.ts'"
}
Add scripts to the package.json for linting with the Angular CLI and for formatting with Prettier.
// 5. Integrate Prettier with TSLint
// tslint.json
{
  "extends": [
    "tslint:recommended",
    "tslint-config-prettier"
  ]
}
Configure TSLint to extend tslint-config-prettier to prevent conflicts between TSLint rules and Prettier formatting.
// 6. Run the linting script
npm run lint
Run the 'lint' script defined in package.json to perform TypeScript code linting.
// 7. Run the formatting script
npm run format
Run the 'format' script defined in package.json to auto-format the code according to Prettier's rules.