arrow-rightgithublinkedinscroll-to-topzig-zag

Angular CLI: Useful tricks

Last Updated On

You might know some angular-cli commands that are available on the official documentation page like ng new [project name], ng generate component [component name], ng test, ng serve etc. However, there are much more commands that are available and not shown in the official doc page.

Shortening the commands

Many commands could be shortened by using shortcuts. For example, instead of writing:

ng generate component my-component

We can type:

ng g c my-component

Regarding this example, Angular CLI can build the following items:

cl: class

c: component (as in the example above)

d: directive

e: enum

m: module

p: pipe

s: service

Applying CSS Preprocessors out of the box

You can use LESS, SASS/SCSS or pure CSS in your project. As you might know, pure CSS is used by default. To modify this behavior, the following parameter should be used

For SCSS:

ng new awesome-project --style=scss

For LESS:

ng new awesome-project --style=less

Sidenote: Angular compiles all SCSS and LESS files and embeds them into index.html. There’re no sourcemaps available during development. To enable sourcemaps, the extra parameter –extract-css=true should be passed into package.json:

...
"scripts": {
    "ng": "ng",
    "start": "ng serve --extract-css=true",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
},
...

Prefixing

Angular CLI is prefixing all components by default with the app prefix. If we want to change that we need to add the following parameter into project generator:

ng new awesome-project --prefix=awesome

Note: If you want to change your component or directive selector later on, you can go to tslint.json and find/replace the directive-selector / component-selector configurations:

...
"directive-selector": [
    true,
    "attribute",
    "new-selector",
    "camelCase"
],
"component-selector": [
    true,
    "element",
    "new-selector",
    "camelCase"
],
...

Conclusion

If you need quickly build Angular project, CLI is a great tool. When I work on a new project, I usually create it using a following command:

ng new awesome-project --style=scss --prefix=awesome

and then add extract-css=true option into the package.json to be able to see sourcemaps.

And of course, word “awesome” serves here as an example. :-)