How to use `moment.js` with Meteor?

前端 未结 5 539
青春惊慌失措
青春惊慌失措 2020-12-06 11:28

I am wanting to use momentjs with meteor. This is an npm package, so from what I understand, it cannot be used with meteor because meteor uses it\'s own package system. So

5条回答
  •  暖寄归人
    2020-12-06 12:09

    Tyler, i had the same question and for sure many people where trying to find the right answer as soon as possible because this is a easy thing to do even though the people that are using meteor for the first time (as me) have this kind of questions...

    Meteor Package Management

    First of all we will wont be using NPM we will be using 'Meteor' which is been used from the Meteor Package Management AtmosphereJS Also, you will find other amazing packages here...

    So lets start

    Open your terminal and go directly where your App is, yo have to install the right dependencies to do so do this:

    Install the only dependency

    This will work with Meteor 1.*

     meteor add momentjs:moment
    

    Compile your app (You can do it now or later)

    This will add that package to your App, after that compile it again with

    meteor
    

    And go to any file inside of your isClient whichi is this

    if (Meteor.isClient) {   }
    

    and you can use the 'moment' method in the same way like they show on their website MomentJs!

    Example

    to give you an example, this is how i'm using in my meteor app

    moment(dateToPass).fromNow();
    

    because i'm using Mongo the original Data looks like this.

    "createdAt" : ISODate("2014-12-12T04:01:21.768Z")
    

    i'll have to do a Simple find query to get it your data and then you can handle your data like this (This code will give you an idea of how i'm using the CreatedAt value that holds a Date() to use it with MomentJS)

    var theItemsOnTheArray = SomeArray.find();
    var dateToPass;
    theItemsOnTheArray.forEach(function (item) { dateToPass = item.createdAt });
    return moment(dateToPass).fromNow();
    

    The result will be

    // 3 years ago
    // 2 years ago
    // 21 hours ago
    // in 3 hours
    // 5 minutes ago
    

    Instead of:

    Thu Dec 11 2014 20:14:08 GMT-0800 (PST)
    

    I hope its useful for any of you, if you think it has valuable info please +1 ;) thanks!

提交回复
热议问题