nuxt-community / date-fns-module

Modern JavaScript date utility library - date-fns for Nuxt.js
MIT License
78 stars 8 forks source link

nuxt 3 support ? #62

Open productdevbook opened 3 years ago

productdevbook commented 3 years ago

repo: https://github.com/productfrontenddeveloper/nuxt3_bug

nuxt/bridge#226

jyotirmaybarman commented 3 years ago

Hello, I wrote a plugin for my use case,

import { defineNuxtPlugin } from '#app';

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.provide('format',(rawtime)=>{
    const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
    // let date = new Date("2021-10-30T19:51:27.710Z");
    let date = new Date(rawtime);
    let year = date.getFullYear();
    let month = date.getMonth();
    let day = date.getDate();
    let hh = date.getHours();
    let mm = date.getMinutes();

    let AmOrPm = hh >= 12 ? 'AM' : 'AM';
    hh = (hh % 12) || 12;

    let diffInSec = Math.floor((Date.now() - date) / 1000);
    if(diffInSec < 30){
        return  'Just Now';
    }
    if(diffInSec < 59){
        return  diffInSec + ' seconds ago';
    }
    let diffInMin = Math.floor(diffInSec/60);
    if(diffInMin<59){
        return diffInMin + ' mins ago';
    }
    return months[month] +' '+ day+' '+year+' , '+hh+':'+mm +' '+ AmOrPm;
  });
});

But is it the right way of doing it ? or can I use dateFns as a plugin (I tried but failed to get it working) in nuxt ??

Cast-El commented 1 year ago

Hello I have found a way to import datefns within nuxt3 :

//plugins\datefns.ts
import * as datefns from 'date-fns'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('datefns', datefns)
})
MickL commented 11 months ago

import * as datefns from 'date-fns'

This will import FULL date-fns without tree shaking, even tho you might only use a few functions of it. I highly recommend not doing that.

If you want to use date-fns within your client- or server-code (but not in template) there is no need to use this module! This module is just needed if you want to use date-fns function within your templates.

Be aware that until date-fns 3.0 is released date-fns is not working on edge workers (like Cloudflare Workers or Vercel Edge Functions): https://github.com/unjs/nitro/issues/1889

Cast-El commented 11 months ago

On our project we use only few functions. In that case you can also pick functions you need :

import {format,parse, parseISO, getDay} from 'date-fns'

const datefns: any={
  format,
  parse,
  parseISO,
  getDay
}

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('datefns', datefns)
})