Reputation: 3783
I am going thru a book tutorial to learn TypeScript and AngularJS 2.0:(Become_a_Ninja_with_Angular2).
At some point it explains how to make your own Pipe and goes thru an implementation of moment.js.
In the folder where my project is located I do in CLI: npm install moment
(FYI: The book also tells to do typings install --save --ambient moment-node
, but that throws an error even if I change --ambient
by --global
, also this error happens to not be a problem to use moment.js
as the rest of the code I describe below runs).
Then, as a result of previous CLI, it creates under my project folder: [my project folder]\node_modules\moment
Then in [my project folder]\main.html
, I have a <script>
tag with: `
<script>
System.config({
defaultJSExtensions: true,
map: {
... [plenty of stuff starting with @angular]..
'@angular/platform-browser-dynamic':'node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'rxjs': 'node_modules/rxjs',
'moment':'node_modules/moment/moment'
}
});
System.import('main');
</script>
My custom Pipe looks like this:
import { PipeTransform, Pipe } from '@angular/core';
import * as moment from 'moment';
import 'moment/../locale/fr';
@Pipe({name: 'fromNow'})
export class FromNowPipe implements PipeTransform {
transform(value,args){
let mydate = moment(new Date(value));
console.log(moment.locales());
return mydate.fromNow();
}
}
As you can see in my custom pipe code, to access the locale 'fr'
, I had to add import 'moment/../locale/fr
(what I found by looking at already existing solution on StackOverflow). If this tag was not implemented I had access to 'en'
only. Which means that adding other languages will require to add import 'moment/../locale/[the locale I want available]
.
Anyone has any ideas how to have all the locale
from the lib moment.js with just the single import * as moment from 'moment';
statement?
PS: And I added to [My project folder]\app.module.ts:
import { FromNowPipe } from './custom_pipes/fromnow.pipe';
...
@NgModule({
...
declarations: [...,FromNowPipe],
...
})
...
And somewhere in one of my component I have:
[@Component({
selector: 'ns-mycomponent',
template:`
.. <div>{{ '2016/05/01'|fromNow }}</div>..
`
})
Upvotes: 1
Views: 2407
Reputation: 3783
I found a workaround:
Based on what I wrote in the question, in [my project folder]\main.html
:
System.config({
defaultJSExtensions: true,
map: {
...
}
});
I substitued: 'moment':'node_modules/moment/moment'
with 'moment':'node_modules/moment/min/moment-with-locales.min.js'
In my Pipe file I just kept: import * as moment from 'moment';
at the beginning of the file and it works: all languages are available.
Upvotes: 1