• Stars
    star
    2,447
  • Rank 18,116 (Top 0.4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Static analysis for Angular projects.

npm version Downloads Build Status code style: prettier Conventional Commits Gitter Chat

codelyzer

A set of tslint rules for static code analysis of Angular TypeScript projects.
(If you are using ESLint check out the new angular-eslint repository.)

You can run the static code analyzer over web apps, NativeScript, Ionic, etc.

Vote for your favorite feature here. For more details about the feature request process see this document

How to use?

Angular CLI

Angular CLI has support for codelyzer. In order to validate your code with CLI and the custom Angular specific rules just use:

ng new codelyzer
ng lint

Note that by default all components are aligned with the style guide so you won't see any errors in the console.

Angular Seed

Another project which has out of the box integration with codelyzer is angular-seed. In order to run the linter you should:

# Skip if you've already cloned Angular Seed
git clone https://github.com/mgechev/angular-seed

# Skip if you've already installed all the dependencies of Angular Seed
cd angular-seed && npm i

# Run all the tslint and codelyzer rules
npm run lint

Note that by default all components are aligned with the style guide so you won't see any errors in the console.

Custom Setup

Preset

You can use the tslint-angular preset. All you need is:

npm i tslint-angular

After that create a tslint.json file with the following configuration:

{
  "extends": ["tslint-angular"]
}

Run the linter with:

./node_modules/.bin/tslint -c tslint.json

TSLint will now complain that there are rules which require type checking. In order to fix this, use the -p config option:

./node_modules/.bin/tslint -p tsconfig.json -c tslint.json

Custom Installation

You can easily use codelyzer with your custom setup:

npm i codelyzer tslint @angular/compiler @angular/core

A. Using codelyzer package in PATH

Create the following tslint.json file like:

{
  "extends": ["codelyzer"],
  "rules": {
    "component-class-suffix": true,
    "component-max-inline-declarations": true,
    "component-selector": [true, "element", "sg", "kebab-case"],
    "contextual-lifecycle": true,
    "directive-class-suffix": true,
    "directive-selector": [true, "attribute", "sg", "camelCase"],
    "no-attribute-decorator": true,
    "no-conflicting-lifecycle": true,
    "no-forward-ref": true,
    "no-host-metadata-property": true,
    "no-input-rename": true,
    "no-inputs-metadata-property": true,
    "no-lifecycle-call": true,
    "no-output-native": true,
    "no-output-on-prefix": true,
    "no-output-rename": true,
    "no-outputs-metadata-property": true,
    "no-pipe-impure": true,
    "no-queries-metadata-property": true,
    "no-unused-css": true,
    "prefer-inline-decorator": true,
    "prefer-output-readonly": true,
    "template-banana-in-box": true,
    "template-conditional-complexity": [true, 4],
    "template-cyclomatic-complexity": [true, 5],
    "template-i18n": [true, "check-id", "check-text"],
    "template-no-negated-async": true,
    "template-use-track-by-function": true,
    "use-component-selector": true,
    "use-component-view-encapsulation": true,
    "use-lifecycle-interface": true,
    "use-pipe-transform-interface": true
  }
}

To run TSLint with this setup you can use one of the following alternatives:

  1. Install codelyzer globally npm install -g codelyzer

  2. Run TSLint from a package.json script by adding a script like tslint . to your package.json, similar to:

"scripts": {
  ...
  "lint": "tslint .",
  ...
},

Then run npm run lint

B. Using codelyzer from node_modules directory

Now create the following tslint.json file where your node_modules directory is:

{
  "rulesDirectory": ["node_modules/codelyzer"],
  "rules": {
    "component-class-suffix": true,
    "component-max-inline-declarations": true,
    "component-selector": [true, "element", "sg", "kebab-case"],
    "contextual-lifecycle": true,
    "directive-class-suffix": true,
    "directive-selector": [true, "attribute", "sg", "camelCase"],
    "no-attribute-decorator": true,
    "no-conflicting-lifecycle": true,
    "no-forward-ref": true,
    "no-host-metadata-property": true,
    "no-input-rename": true,
    "no-inputs-metadata-property": true,
    "no-lifecycle-call": true,
    "no-output-native": true,
    "no-output-on-prefix": true,
    "no-output-rename": true,
    "no-outputs-metadata-property": true,
    "no-pipe-impure": true,
    "no-queries-metadata-property": true,
    "no-unused-css": true,
    "prefer-inline-decorator": true,
    "prefer-output-readonly": true,
    "template-banana-in-box": true,
    "template-conditional-complexity": [true, 4],
    "template-cyclomatic-complexity": [true, 5],
    "template-i18n": [true, "check-id", "check-text"],
    "template-no-negated-async": true,
    "template-use-track-by-function": true,
    "use-component-selector": true,
    "use-component-view-encapsulation": true,
    "use-lifecycle-interface": true,
    "use-pipe-transform-interface": true
  }
}

Next you can create a component file in the same directory with name component.ts and the following content:

import { Component } from '@angular/core';

@Component({
  selector: 'codelyzer',
  template: ` <h1>Hello {{ name }}!</h1> `,
})
class Codelyzer {
  name: string = 'World';

  ngOnInit() {
    console.log('Initialized');
  }
}

As last step you can execute all the rules against your code with tslint:

./node_modules/.bin/tslint -c tslint.json component.ts

You should see the following output:

component.ts[4, 13]: The selector of the component "Codelyzer" should have prefix "sg" (https://goo.gl/cix8BY)
component.ts[12, 3]: Implement lifecycle hook interface OnInit for method ngOnInit in class Codelyzer (https://goo.gl/w1Nwk3)
component.ts[9, 7]: The name of the class Codelyzer should end with the suffix Component (https://goo.gl/5X1TE7)

Editor Configuration

Note that you need to have tslint plugin install on your editor.

Codelyzer should work out of the box with Atom but for VSCode you will have to open Code > Preferences > User Settings, and enter the following config:

{
  "tslint.rulesDirectory": "./node_modules/codelyzer",
  "typescript.tsdk": "node_modules/typescript/lib"
}

Now you should have the following result:

VSCode Codelyzer

Enjoy!

Changelog

You can find it here.

Recommended configuration

Below you can find a recommended configuration which is based on the Angular Style Guide.

{
  // The rules component-selector and directive-selector have the following arguments:
  // [ENABLED, "attribute" | "element", "prefix" | ["listOfPrefixes"], "camelCase" | "kebab-case"]
  "component-selector": [true, "element", ["cmp-prefix1", "cmp-prefix2"], "kebab-case"],
  "directive-selector": [true, "attribute", ["dir-prefix1", "dir-prefix2"], "camelCase"],

  "component-max-inline-declarations": true,
  "contextual-lifecycle": true,
  "no-conflicting-lifecycle": true,
  "no-host-metadata-property": true,
  "no-input-rename": true,
  "no-inputs-metadata-property": true,
  "no-output-native": true,
  "no-output-on-prefix": true,
  "no-output-rename": true,
  "no-outputs-metadata-property": true,
  "no-queries-metadata-property": true,
  "prefer-inline-decorator": true,
  "template-banana-in-box": true,
  "template-no-negated-async": true,
  "use-lifecycle-interface": true,
  "use-pipe-transform-interface": true,

  // The rules component-class-suffix and directive-class-suffix have the following arguments:
  // [ENABLED, "suffix" | ["listOfSuffixes"]]
  // Where "suffix" is/are your custom(s) suffix(es), for instance "Page" for Ionic components.
  "component-class-suffix": [true, "Component"],
  "directive-class-suffix": [true, "Directive"]
}

Rules Status

Rule Status
component-class-suffix Stable
component-max-inline-declarations Stable
component-selector Stable
contextual-decorator Stable
contextual-lifecycle Stable
directive-class-suffix Stable
directive-selector Stable
import-destructuring-spacing Stable
no-attribute-decorator Stable
no-forward-ref Stable
no-host-metadata-property Stable
no-input-prefix Stable
no-input-rename Stable
no-inputs-metadata-property Stable
no-lifecycle-call Stable
no-output-native Stable
no-output-on-prefix Stable
no-output-rename Stable
no-outputs-metadata-property Stable
no-pipe-impure Stable
no-queries-metadata-property Stable
prefer-inline-decorator Stable
prefer-output-readonly Stable
template-banana-in-box Stable
template-cyclomatic-complexity Stable
template-no-call-expression Stable
template-no-negated-async Stable
template-use-track-by-function Stable
use-component-selector Stable
use-component-view-encapsulation Stable
use-lifecycle-interface Stable
use-pipe-decorator Stable
use-pipe-transform-interface Stable
prefer-on-push-component-change-detection Experimental
no-conflicting-lifecycle Experimental
no-unused-css Experimental
pipe-prefix Experimental
relative-url-prefix Experimental
template-accessibility-alt-text Experimental
template-accessibility-elements-content Experimental
template-accessibility-label-for Experimental
template-accessibility-tabindex-no-positive Experimental
template-accessibility-table-scope Experimental
template-accessibility-valid-aria Experimental
template-click-events-have-key-events Experimental
template-conditional-complexity Experimental
template-i18n Experimental
template-mouse-events-have-key-events Experimental
template-no-any Experimental
template-no-autofocus Experimental
template-no-distracting-elements Experimental
angular-whitespace Deprecated

Disable a rule that validates Template or Styles

Lint rules can be disabled by adding a marker in TypeScript files. More information here.

To disable rules that validate templates or styles you'd need to add a marker in the TypeScript file referencing them.

import { Component } from '@angular/core';

/* tslint:disable:template-use-track-by-function */
@Component({
  selector: 'codelyzer',
  templateUrl: './codelyzer.component.html',
})
class Codelyzer {}

Advanced configuration

Codelyzer supports any template and style language by custom hooks. If you're using Sass for instance, you can allow codelyzer to analyze your styles by creating a file .codelyzer.js in the root of your project (where the node_modules directory is). In the configuration file can implement custom pre-processing and template resolution logic:

// Demo of transforming Sass styles
var sass = require('node-sass');

module.exports = {
  // Definition of custom interpolation strings
  interpolation: ['{{', '}}'],

  // You can transform the urls of your external styles and templates
  resolveUrl(url, decorator) {
    return url;
  },

  // Transformation of the templates. This hooks is quite useful
  // if you're using any other templating language, for instance
  // jade, markdown, haml, etc.
  //
  // NOTE that this method WILL NOT throw an error in case of invalid template.
  //
  transformTemplate(code, url, decorator) {
    return { code: code, url: url };
  },

  // Transformation of styles. This hook is useful is you're using
  // any other style language, for instance Sass, Less, etc.
  //
  // NOTE that this method WILL NOT throw an error in case of invalid style.
  //
  transformStyle(code, url, decorator) {
    var result = { code: code, url: url };
    if (url && /\.scss$/.test(url)) {
      var transformed = sass.renderSync({ data: code, sourceMap: true, outFile: '/dev/null' });
      result.source = code;
      result.code = transformed.css.toString();
      result.map = transformed.map.toString();
    }
    return result;
  },

  // Custom predefined directives in case you get error for
  // missing property and you are using a template reference
  predefinedDirectives: [{ selector: 'form', exportAs: 'ngForm' }],

  // None = 0b000, Error = 0b001, Info = 0b011, Debug = 0b111
  logLevel: 0b111,
};

Contributors

mgechev wKoza rafaelss95 preslavsh mohammedzamakhan rokerkony
mgechev wKoza rafaelss95 preslavsh mohammedzamakhan rokerkony
GregOnNet alan-agius4 kevinphelps eppsilon csvn ghsyeung
GregOnNet alan-agius4 kevinphelps eppsilon csvn ghsyeung
Kobzol mattlewis92 lazarljubenovic sagittarius-rev connor4312 Foxandxss
Kobzol mattlewis92 lazarljubenovic sagittarius-rev connor4312 Foxandxss
gbilodeau NagRock Hotell Martin-Wegner comfroels plantain-00
gbilodeau NagRock Hotell Martin-Wegner comfroels plantain-00
nexus-uw alexkpek loktionov129 alisd23 aboyton bmvantunes
nexus-uw alexkpek loktionov129 alisd23 aboyton bmvantunes
Moeriki sneas EmmanuelDemey eromano Manduro karol-depka
Moeriki sneas EmmanuelDemey eromano Manduro karol-depka
leosvelperez muhammadghazali PapsOu rwlogel robzenn92 rtfpessoa
leosvelperez muhammadghazali PapsOu rwlogel robzenn92 rtfpessoa
santoshyadav198613 scttcper stschake tmair YogliB cexbrayat
santoshyadav198613 scttcper stschake tmair YogliB cexbrayat
clydin reduckted someblue
clydin reduckted someblue

License

MIT

More Repositories

1

javascript-algorithms

💻 JavaScript implementations of computer science algorithms
JavaScript
7,808
star
2

angularjs-style-guide

📚 Community-driven set of best practices for AngularJS application development
4,984
star
3

revive

🔥 ~6x faster, stricter, configurable, extensible, and beautiful drop-in replacement for golint
Go
4,584
star
4

angular-seed

🌱 [Deprecated] Extensible, reliable, modular, PWA ready starter project for Angular (2 and beyond) with statically typed build and AoT compilation
TypeScript
4,574
star
5

angular-performance-checklist

⚡ Cheatsheet for developing lightning fast progressive Angular applications
4,027
star
6

google-interview-preparation-problems

leetcode problems I solved to prepare for my Google interview.
JavaScript
3,090
star
7

angularjs-in-patterns

AngularJS in patterns - this repository provides different look into AngularJS. It contains information where different design patterns are used inside the framework or any Angular application.
JavaScript
1,956
star
8

ngrev

Tool for reverse engineering of Angular applications
TypeScript
1,553
star
9

mk.js

Canvas implementation of basic fighting game which allows multiplayer over the network.
JavaScript
1,504
star
10

angular2-style-guide

[Deprecated] Community-driven set of best practices and style guidelines for Angular 2 application development
1,205
star
11

injection-js

Dependency injection library for JavaScript and TypeScript in 5.1K. It is an extraction of the Angular's ReflectiveInjector which means that it's well designed, feature complete, fast, reliable and well tested.
TypeScript
1,149
star
12

jscapture

Screen recording and capturing with pure client-side JavaScript.
JavaScript
797
star
13

tiny-compiler

A tiny evaluator and compiler of arithmetic expressions.
JavaScript
768
star
14

ngx-quicklink

Quicklink prefetching strategy for the Angular router
TypeScript
737
star
15

guess-next

🔮 Demo application showing the integration of Guess.js with Next.js
JavaScript
526
star
16

aspect.js

JavaScript library for aspect-oriented programming using modern syntax.
TypeScript
472
star
17

angular-webrtc

Demo for my blog post at http://goo.gl/LCOSsI
ApacheConf
307
star
18

switching-to-angular2

TypeScript
285
star
19

memo-decorator

Decorator which applies memoization to a method of a class.
TypeScript
256
star
20

js-vnc-demo-project

Demo project for the class Advanced JavaScript at the department mathematics and informatics in Sofia University.
JavaScript
186
star
21

is-esm

🌳 CLI tool which checks if a package is distributed in ECMAScript module format. Helps you reason if the package is tree-shakable.
JavaScript
179
star
22

angular-immutable

Simple directive, which allows binding to Immutable.js collections.
JavaScript
166
star
23

ngast

Parser for Angular projects.
TypeScript
164
star
24

angular-aop

Library for aspect-oriented programming with AngularJS.
JavaScript
161
star
25

tslint-angular

Recommended tslint configuration for Angular applications.
161
star
26

ngx-hover-preload

🖱 Preload Angular lazy-loaded routes on mouse over
TypeScript
159
star
27

mk-tfjs

Play MK.js with TensorFlow.js
JavaScript
156
star
28

ReactChat

WebRTC chat with ReactJS
JavaScript
153
star
29

ngworld

Generate a Minecraft/Christmas-like world out of an Angular application.
TypeScript
142
star
30

scalable-architecture-demo

TypeScript
134
star
31

github-contributors-list

Node.js script, which outputs all the contributors for given open GitHub project
JavaScript
131
star
32

ngresizable

Simple, tree-shakable, AoT, Universal and Web Worker friendly resizable component for Angular (2 and beyond).
TypeScript
117
star
33

angular2-hot-loader

[NOT MAINTAINED] Angular 2 hot loader
TypeScript
115
star
34

light-angularjs

Light AngularJS implementation for my slides "Lightweight AngularJS"
JavaScript
110
star
35

movement.js

Gesture recognition with JavaScript and HTML5.
JavaScript
106
star
36

angular-vnc

VNC client implemented with AngularJS and Yeoman
JavaScript
99
star
37

ngx-tfjs

🤖 TensorFlow.js bindings for Angular
TypeScript
95
star
38

real-world-bazel

The real world Angular example app moved to Bazel
TypeScript
90
star
39

angular-transitions

Pre-defined set of CSS3 transformation which can be used with ng-view, ui-view, ng-repeat, ng-show, ng-hide. Both the 1.1.5 and 1.2.0 APIs are supported.
CSS
90
star
40

angular-tfjs-demo

A demo application with TensorFlow.js bindings for Angular.
TypeScript
83
star
41

angular2-ngc-rollup-build

Simple build for "Hello world!" Angular 2 application with ngc and rollup.
HTML
81
star
42

angular2-github-app-bootstrap

Exercise for building simple Angular 2 apps
JavaScript
79
star
43

blog.mgechev.com

My personal blog.
JavaScript
70
star
44

dotfiles

My dot files.
Shell
67
star
45

react-reorderable

Simple react sortable component (for more advanced cases use react-dnd).
JavaScript
63
star
46

devtools-vnc

VNC client for Chrome Devtools
JavaScript
61
star
47

ngx-flamegraph

Flame graph for stack trace visualization written in Angular
TypeScript
58
star
48

cli-builders-demo

Demo showing how to develop a builder using the Angular CLI Architect API.
TypeScript
56
star
49

electron-typescript-boilerplate

Electron TypeScript starter (intended mostly for personal projects). Fork of https://github.com/szwacz/electron-boilerplate.
JavaScript
54
star
50

angular-ivy-demo

Demo repository showing how ivy allows significant API simplification.
TypeScript
53
star
51

mlx

Data-driven bundling
TypeScript
48
star
52

optimizing-an-angular-application

Code for my ngconf talk "Optimizing an Angular Application".
TypeScript
48
star
53

ngx-gh

Automatic deployments to GitHub pages directly from the Angular CLI 🚀
TypeScript
45
star
54

data-adapter

Data adapter useful in data serialization when talking with external services.
TypeScript
45
star
55

react-pstate

Persistence of the state of ReactJS component
JavaScript
43
star
56

hybrid-rendering

TypeScript
42
star
57

playground

Initial experience with different programming languages
JavaScript
40
star
58

bazel-demo

Simple demo for building a TypeScript project with Bazel.
TypeScript
40
star
59

angular-hybrid-rendering

TypeScript
39
star
60

plainvm

plainvm allows you to control multiple virtual machines which are distributed among many hosts through your browser.
JavaScript
38
star
61

angular2-simple-build

Simple build for "Hello world!" Angular 2 application.
TypeScript
37
star
62

gemini-angular-drawing-demo

TypeScript
37
star
63

versionable-collections

Collection optimized for AngularJS 1.x one-way bindings
JavaScript
33
star
64

typed-calc

Interpreter for simply typed lambda calculus implemented in JavaScript λ
JavaScript
33
star
65

ngx-circular-player

Circular player for Angular
TypeScript
32
star
66

swagger-typescript-fetch-api

Swagger codegen for TypeScript Fetch API.
HTML
32
star
67

angular2-stripe-demo

TypeScript
30
star
68

blobreader

Simple interface for reading blobs sequentially
JavaScript
28
star
69

ts-rpc

RPC protocol with services defined via TypeScript interfaces.
TypeScript
27
star
70

performance-patterns

TypeScript
27
star
71

podcast

Website of the Programming Podcast
TypeScript
26
star
72

dots

Implements the wildcard file matching in Go used by golint, go test etc.
Go
25
star
73

purely-fast

TypeScript
25
star
74

ng-tutorial

Platform for AngularJS interactive tutorials
JavaScript
25
star
75

ELang

Simple programming language created for educational purpose
Java
24
star
76

angular-realworld-example-app-qucklink

TypeScript
22
star
77

gently-js

Module which returns the offensive words in a string. A soft reminder to be nicer to each other ❤️.
JavaScript
22
star
78

optimizing-apps-angular-demo

Demo application for my talk on optimizing Angular apps
TypeScript
21
star
79

ngmigrate

Automated migration of <template> to <ng-template> for Angular 4+
JavaScript
20
star
80

dynamic-route-creator

[DEPRECATED] Demo for dynamically defining routes in Angular 2
TypeScript
19
star
81

guess-js-angular-demo

TypeScript
18
star
82

lazy-loading-routes-angular2

WARNING: Uses deprecated APIs.
JavaScript
18
star
83

angular2-hot-loader-demo

Demo of the Angular 2 hot loader prototype
TypeScript
18
star
84

guess-js-react-demo

JavaScript
17
star
85

angular2-rollup-build

Simple build for "Hello world!" Angular 2 application with rollup.
HTML
17
star
86

svg-design-patterns

This repository contains UML class diagrams of some design and architectural patterns.
17
star
87

getting-started-with-angular

Code for the second edition of the book "Switching to Angular 2", with title "Getting started with Angular".
TypeScript
17
star
88

programming-podcast-samples

TypeScript
16
star
89

react-di-demo

Demo for my blog post "Implementing Angular's Dependency Injection in React. Understanding Element Injectors."
JavaScript
16
star
90

kitty-cinema

HTML
15
star
91

code-splitting-web-dev

TypeScript
15
star
92

react-drag

JavaScript
15
star
93

ivy-library-distribution-demo

TypeScript
14
star
94

angular-bazel-hello-world

Simple Angular app with Bazel configuration
HTML
13
star
95

viewchildren-contentchildren-demo

TypeScript
12
star
96

top-packages

TypeScript
12
star
97

v8-sorting-test

Testing the sorting performance of Google's V8 JavaScript engine.
Perl
12
star
98

guess-angular

TypeScript
11
star
99

immutable-differ

Work in progress.
TypeScript
11
star
100

eap-feedback

11
star