Add moment to angular 2 (angular cli)

I followed the instructions on the GitHub page. But I can not get it to work in my application.
Here is what I did:

  1. installed moment: npm install moment --save
  2. installed moment ts: npm install @types/moment --save
  3. An imported moment in one of my components: import * as moment from 'moment';

I get the following error: img

Any ideas?

+6
source share
4 answers

To install a third-party library in the latest version of angular-cli simply simplified. (Version of webpack, not systemjs).

Go to your angular-cli.json in the project root directory and configure it so

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

Then finally in any.component.ts you can import it like this:

 import { Component, OnInit } from '@angular/core'; import * as moment from 'moment'; @Component({ selector: '[id=home]', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { constructor() { } ngOnInit () { console.log('today is', moment()); } } 
+14
source

You just need to enable it to enable the moment using CommonJS syntax, not import. Try the following:

 let moment = require('moment'); 

This is because the moment is not yet as an ES6 module, and as such will not work with the new import syntax.

UPDATE:

When I think about it, I used this approach only in my unit tests. Using it in your application may not work well, because this approach uses node require , which cannot be used on the client side.

However, when using Moment in your components, you can use angular2-moment . Full installation instructions can be found on the GitHub page, but usage is as follows:

 <div>today is {{ Date.now() | amDateFormat:'LL' }}</div> 

There are several other pipes you can use, all of which are documented on the GitHub page.

UPDATE 2:

Starting with version v2.10.0, Moment now supports ES6 syntax, so you can use any ES6 import syntax instead of require .

+1
source

I had to upgrade my cli version: npm uninstall -g angular-cli @angular/cli npm cache clear npm install -g @angular/ cli@latest

+1
source

This topic is a bit old, but that was what I needed. The moment now comes with a type definition file, and @types/moment now deprecated in favor of this new file. In order to instantly work with other libraries that extend type definitions from the moment, for example fullcallendar , you also need to override the default module resolution in your tsconfig.app.json

 "compilerOptions": { ... "paths": { "moment": [ "../node_modules/moment/moment.d.ts", "../node_modules/moment/min/moment.min.js" ] }, }, 

You also want to update your angular.json section to include a moment:

  "build": { ..., "options": { ... "scripts": [ "node_modules/moment/min/moment.min.js"] }, 
+1
source

All Articles