Steps to add Moment.js to Angular-CLI

date updated: 5 Jun 2017

Step 1: in terminal e.g. using MacOS

npm install -g @angular/cli@latest

Step 2: again in terminal

ng new angular-cli-v1-1-0-momentjs
cd angular-cli-v1-1-0-momentjs

Step 3: in terminal

npm install moment --save

Step 4*: in terminal

npm install @types/moment --save

This step 4 is an optional step, you decide for yourself.


Step 5: in angular-cli.json

{
...
"apps": [
...
"scripts": [
"../node_modules/moment/min/moment.min.js"
]
...
]
...
}

Step 6a: in app.component.ts

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

import * as moment from 'moment'; // add this 1 of 4

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';

constructor() {
let now = moment(); // add this 2 of 4
console.log('hello world', now.format()); // add this 3 of 4
console.log(now.add(7, 'days').format()); // add this 4of 4
}

}

Choose between step 6a or step 6b. Spot the difference.


Step 6b: in app.component.ts (I think this Step 6b doesn’t work any more. I haven’t tried it yet. Will try it soon!)

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';

constructor() {
let moment = require('moment'); // add this 1 of 4
let now = moment(); // add this 2 of 4
console.log('hello world', now.format()); // add this 3 of 4
console.log(now.add(7, 'days').format()); // add this 4 of 4
}

}

Step 7a: in terminal

ng serve

Open your browser e.g. Chrome and navigate to http://localhost:4200


Step 7b*: in terminal

ng serve --aot

This step 7b is an optional step. It is to see for yourself that it works with AOT compilation. Similar to Step 7a, open your browser e.g. Chrome and navigate to http://localhost:4200


Evidence

Questions to answer for further learning

  1. Is it really necessary to install types (see 3rd Party Library Installation)?
  2. There are 6a or 6b as some suggested an alternative approach (see this stackoverflow q&a). Which approach is more performance optimised for minimal use of moment.js in angular project?