Giter Club home page Giter Club logo

dayjs-module's Introduction

@nuxtjs/dayjs

code style: prettier donate: Patreon License: MIT NPM version All Contributors NPM downloads codecov

The best way to use Day.js easily in your Nuxt 2 project.

Looking for a Nuxt 3 alternative? Try out:

Installation

$ yarn add @nuxtjs/dayjs # or npm install

Usage

1. Register dayjs module to your Nuxt Application

export default {
  // ...
  modules: [
    '@nuxtjs/dayjs'
  ],

  // Optional
  dayjs: {
    locales: ['en', 'ja'],
    defaultLocale: 'en',
    defaultTimeZone: 'Asia/Tokyo',
    plugins: [
      'utc', // import 'dayjs/plugin/utc'
      'timezone' // import 'dayjs/plugin/timezone'
    ] // Your Day.js plugin
  }
  // ...
}

2. Use $dayjs on Context, Vue instance

with Context

<script>
export default {
  asyncData({ $dayjs }) {
    return {
      now: $dayjs().format('YYYY/MM/DD')
    }
  }
}
</script>

with Vue instance

<script>
export default {
  data() {
    return {
      latestClicked: null
    }
  },
  methods: {
    handleClickButton() {
      this.latestClicked = this.$dayjs().format('YYYY/MM/DD')
    }
  }
}
</script>

For Typescript users

Add the types to your "types" array in tsconfig.json after the @nuxt/types entry.

For dayjs plugins, add their relative types like dayjs/plugin/_pluginName_.

tsconfig.json

{
  "compilerOptions": {
    "types": [
      "@nuxt/types",
      "@nuxtjs/dayjs",
      "dayjs/plugin/relativeTime",
    ]
  }
}

Development

$ git clone https://github.com/nuxt-community/dayjs-module.git
$ cd @nuxtjs/dayjs
$ yarn

License

MIT @potato4d

Note

This project generated by create-nuxt-module

Contributors

Thanks goes to these wonderful people (emoji key):


Takuma HANATANI(@potato4d)

๐Ÿ’ป ๐Ÿ› ๐Ÿ“– ๐Ÿ’ก ๐Ÿ’ฌ ๐Ÿ‘€

Bryan Daniel Velastegui Lucero

๐Ÿ’ป

Wei

๐Ÿ’ป

ใ‹ใšใˆใ‚‚ใ‚“

๐Ÿ“–

Daiki Ojima

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

dayjs-module's People

Contributors

a65162 avatar allcontributors[bot] avatar cmnaoyaoshiro avatar daikiojm avatar danielroe avatar dependabot[bot] avatar harlan-zw avatar kapcash avatar potato4d avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dayjs-module's Issues

Discussion for @nuxtjs/dayjs version 2

This PR is created based on conversation in #396, and is to clarify what we need to support Nuxt3, Nuxt Bridge, and to modernize the code base for the new era of Nuxt ecosystem. Modernization could include refinement of module API and DX since the result will be a major update.


TL;DR

I would like to know thoughts on the following topics.

  • We should Nuxt 3 (I believe)
  • Should we should Nuxt Bridge?
  • Should we await for the new test utils, or should we prioritize fast release with dedicated manual testing?
  • Is there things to add, refine, or delete in module API and DX in version 2?
  • At first, what are the author(s) opinions?

Current situation

First of all, it is reported that @nuxtjs/dayjs module doesn't work with either Nuxt 3 (#376) or Nuxt Bridge (#387), which is of course the main focus for the time being.

Second, @nuxtjs/dayjs module doesn't provide composable(s) for composition API, which had been unavailable when this module was introduced. This will be a topic to discuss, and I don't have a strong opinion to be honest.

Third, the code base is (as far as I see) based on defacto standard of Nuxt 2 ecosystem (e.g., main logic in lib directory, defining declaration file separately). Nuxt team provides the new module starter template (nuxt/starter), so it will be a good time to migrate.

Fourth, the main logic of @nuxtjs/dayjs (i.e. lib/module.js) is written in JavaScript. Being written in JavaScript itself is not a thing that need to be "fixed", but Nuxt 3 ecosystem is now more TypeScript-friendly or even TypeScript-centric in most parts, so relying on it will be beneficial for future maintainability

Nuxt 3 support

With the new module template, supporting Nuxt 3 with the same API as the current version is just a few-hours task, except some aspects such as testing, as I already demonstrated in #396.

Nuxt Bridge support

Due to the lack of playground for Nuxt Bridge in the new module template, and some differences in Nuxt 2/3 API, we need more dedicated work on Nuxt Bridge support. We might be able to skip this task for now so that we can iterate the cycle of development more fast.

I would like to here your opinion for this point as well as providing composable(s).

Modernization as a part of Nuxt ecosystem

I mean it by modernization here to make @nuxtjs/dayjs module aligned with other Nuxt ecosystem, especially with Nuxt core modules. While we could make use of the legacy code base, I believe migration to the new normal will provide more benefits for us. For example, developers in the community will be more likely to be so confident to understand the code base and to contribute to this repository. Since no one can guarantee that the person maintain something forever, keeping parts of ecosystem aligned with others is what we can do for the community (cf. ADDRESSING ARCHITECTURAL ISSUES section of The process: Making Vue 3).

But, we should be aware of that Nuxt 3 ecosystem is still a work in progress. Some tools such as testing utils are not yet ready and stable. Here, we should make a decision about our roadmap for version 2 of @nuxtjs/dayjs module.

Fast release with few possible testing await core system mature, or even eclectic.

Again, I don't have a strong opinion. I'm just not willing to contribute based on authors decisions.

DX and API refinement

@danielroe suggested in #396 to provide composable(s) instead of injecting a plugin into Nuxt context.
I added module option validation logic in #396 for fast fail instead of runtime error.

What version 2 should provide and how is kinda open-question and needs feedback community.
I love to hear what features people need and implement them.

(By the way, I'm not sure whether there are differences between modules that is managed in nuxt-community organization and personal repository. Is the former more like community-driven one while the latter is owned by the person?)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/node to v16.18.97
  • fix(deps): update dependency dayjs to v1.11.11
  • chore(deps): update dependency @types/puppeteer to v7
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
  • circleci/node 16.13.1-browsers
npm
package.json
  • consola ^2.10.1
  • dayjs ^1.10.4
  • @nuxt/types 2.15.8
  • @nuxtjs/module-test-utils 1.6.3
  • @types/consola 1.0.0
  • @types/jest 27.5.2
  • @types/jsdom 21.1.6
  • @types/node 16.18.91
  • @types/puppeteer 5.4.7
  • all-contributors-cli 6.24.0
  • codecov 3.8.3
  • jest 27.5.1
  • nuxt 2.16.3
  • prettier 2.8.8
  • puppeteer 15.5.0
  • standard-version 9.5.0
  • ts-jest 27.1.5
  • typescript 5.0.4

  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Nuxt warning occurs when this module is used

I'm now seeing this warning appear using v1.4.0.

In my devDependencies: "@nuxtjs/dayjs": "^1.4.0"
in my nuxt.config.js: @nuxtjs/dayjs

The command 'nuxt build' finished but did not exit after 5s
This is most likely not caused by a bug in Nuxt
Make sure to cleanup all timers and listeners you or your plugins/modules start.
Nuxt will now force exit
DeprecationWarning: Starting with Nuxt version 3 this will be a fatal error

image

Plugins support?

Evening!
Can you enable dayjs plugins (e.g. customParseFormat) in the current implementation of the module?
Thanks in advance.

[Nuxt Bridge] Build tries to import plugin without file format

Hello ๐Ÿ‘‹

Using the latest Nuxt Bridge and Nuxt DayJS set in buildModules and in devDependencies, with both Vite enabled and disabled.

I build nuxi build and start it nuxi start and I got immediately a critical error.

Cannot find module '/project/.output/server/node_modules/dayjs/plugin/relativeTime' imported from /project/.output/server/chunks/app/server.mjs
Did you mean to import dayjs/plugin/relativeTime.js?

The file is in that folder but it tries to import it without the file format.

https://github.com/nuxt-community/dayjs-module/blob/master/lib/plugin.js#L4

Just to test, I tried to add .js in that line and it fixed. However, I'm not sure if that is the correct behavior to define a specific file format. I think that maybe is there another underlying bug from Nuxt.

Thank you very much!

CC: @danielroe @potato4d

Typescript support for dayjs with Plugins

Hello,

I added dayjs to next with this module and configured it as follow:

  dayjs: {
    locales: ['de', 'en'],
    defaultLocale: 'de',
    defaultTimeZone: 'Europe/Berlin',
    plugins: ['utc', 'timezone', 'localizedFormat'],
  },

If I use

return this.$dayjs().tz(this.$store.state.user.timezone).format('LLL ZZ')

in a component, I get the following typescript error

Property 'tz' does not exist on type 'Dayjs'.Vetur(2339)

My workaround is

return (this.$dayjs() as any).tz(this.$store.state.user.timezone).format('LLL ZZ')

currently but I normally try to eliminate all any's in my projects.

Is there further typescript support?

PS: Of course I added nuxtjs/dayjs to the typescript types configuration.

Plugin relativetime crush building on linux

When I run builing (yarn run build) on linux (Ubuntu 19.x) server the error appears:

ERROR in ./.nuxt/dayjs-plugin.js
Module not found: Error: Can't resolve 'dayjs/plugin/relativetime' in '/home/sink/bychords/.nuxt'
 @ ./.nuxt/dayjs-plugin.js 6:13-49
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js

My configuration:
  dayjs: {
    locales: ['en', 'ru'],
    defaultLocale: 'en',
    plugins: ['utc', 'timezone', 'relativetime'],
  },

On windows i don't have any problems with it

Implementing advanced formatting

dayjs documentation says to add library as such:

var advancedFormat = require('dayjs/plugin/advancedFormat')
dayjs.extend(advancedFormat)
dayjs().format('Q Do k kk X x')

What is the best way to add the advanced format plugin to dayjs library in nuxt project?

Library is added in nuxt.config
modules: { 'nuxt-dayjs-module' }

This adds dayjs to root instance in components. ie: this.dayjs

Have tried importing the plugin in a component but this does not work.

Any advice appreciated!

weekStart configuration

Hello, I'm not seeing a way to configure weekStart in the documentation. Is that something that is supported with this module? I attempted to put the configuration into the 'locales' array in nuxt.config.js but got errors for having an object in the array, so I'm assuming that's not the correct way to do it.

Use $dayjs with Vue.mixin

How can I use $dayjs with a Vue.mixin?

Steps:

  1. Installed: yarn add @nuxtjs/dayjs
  2. Added '@nuxtjs/dayjs' to modules: [] in nuxt.config.js
  3. Created dayjs.js in /plugins
  4. Added {src: '~/plugins/dayjs'}, to plugins: [] in nuxt.config.js

dayjs.js

import Vue from 'vue'

Vue.mixin({
  methods: {

    format_date: function (date) {
        return this.$dayjs(date).format('L');
    }

  }
})

Current version does not work

When adding nuxt-dayjs-module to modules I'm getting an error when running npm run dev:

FATAL  Unexpected token {                                                                                                                                                                                                                                          13:01:06

  import { resolve } from 'path'
  ^

  SyntaxError: Unexpected token {
  at Object.compileFunction (vm.js:383:10)
  at Generator.next (<anonymous>)

Nuxt3 Support

UPDATE: 3rd party module available https://github.com/fumeapp/dayjs

I have written a DayJS plugin for nuxt3 and so far its working pretty well:

plugnis/dayjs.ts

import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime.js'
import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin((nuxtApp) => {
  dayjs.extend(relativeTime)
  nuxtApp.provide('dayjs', dayjs)
})

declare module '#app' {
  interface NuxtApp {
    $dayjs: dayjs.Dayjs
 }
}

I assume next steps are to transfer this into the template/runtime format and plug in the locale config.

Filters

Any plans to include filters out of the box? Would a PR including some be accepted?

Vite support

For this module to be used with vite we'll need to convert the dynamic require calls to imports.

See nuxt/vite#120

Moving to nuxt-community

Hi @potato4d ๐Ÿ˜Š

If you are interested in moving your awesome module to nuxt-community and @nuxtjs/ that's more than welcome. You still will be code owner and maintainer of course just a little bit more official and others can discover/trust it easier and help for maintenance.

Locales and defaultLocale

Hey! Thanks for your module

I have set default locale and locales, but who should switch them and where?

    ...
    locales: ['ru', 'en'],
    defaultLocale: 'en',

OK, i18n module changed language, what's next?

Error on creating a new locale, for Latin language.

Based on the description of some issues here and StackOverflow about updateLocale, I tried to create a new locale but still my locale can't resolve in build.

Package Version
nuxt ^2.17.0
@nuxtjs/dayjs ^1.4.1

nuxt.config.js

plugins: [
  '~/plugins/dayjs.js',
],

modules: [
 '@nuxtjs/dayjs'
],

dayjs: {
  locales: ['en', 'de', 'la'], // la for Latin language
  defaultLocale: 'de',
  plugins: [
    'utc',
    'timezone',
    'customParseFormat',
    'advancedFormat',
  ],
},

~/plugins/dayjs.js

export default function ({ $dayjs }) {
  $dayjs.locale('la', {
    name: 'la',
    weekdays: ["Dies Lunae", "Dies Martis", "Dies Mercurii", "Dies Iovis", "Dies Veneris", "Dies Saturni", "Dies Solis"],
    weekdaysShort: ["Lun.", "Mar.", "Mer.", "Iov.", "Ven.", "Sat.", "Sol."],
    weekdaysMin: ["Lu.", "Ma.", "Me.", "Jo.", "Ve.", "Sa.", "So."],
    weekStart: 1,
    yearStart: 4,
    months: ["Ianuarius", "Februarius", "Martius", "Aprilis", "Maius", "Iunius", "Iulius", "Augustus", "September", "October", "November", "December"],
    monthsShort: ["Ian.", "Feb.", "Mar.", "Apr.", "Mai", "Iun.", "Iul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."],
    ordinal: n => `${n}ยบ`,
    formats: {
      LTS: 'h:mm:ss A',
      LT: 'h:mm A',
      L: 'MM/DD/YYYY',
      LL: 'MMMM D, YYYY',
      LLL: 'MMMM D, YYYY h:mm A',
      LLLL: 'dddd, MMMM D, YYYY h:mm A',
      l: 'D/M/YYYY',
      ll: 'D MMM, YYYY',
      lll: 'D MMM, YYYY h:mm A',
      llll: 'ddd, MMM D, YYYY h:mm A'
    },
    relativeTime: {
      future: 'in %s',
      past: 'ante %s',
      s: 'paucis momentis',
      m: 'minuto',
      mm: '%d minutis',
      h: 'hora',
      hh: '%d horis',
      d: 'die',
      dd: '%d diebus',
      M: 'mense',
      MM: '%d menses',
      y: 'anno',
      yy: '%d annis'
    },
    meridiem: (hour, minute, isLowercase) => {
      return hour > 12 ? 'PM' : 'AM'
    }
  })
}

Problem

I get Nuxt Fatal Error for not founding the la locale on build:

ERROR in ./.nuxt/dayjs-plugin.js
Module not found: Error: Can't resolve 'dayjs/locale/la' in '/Users/ari/Documents/Projects/noeku-boilerplate/.nuxt'
 @ ./.nuxt/dayjs-plugin.js 5:0-25
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ ./.nuxt/nuxt-speedkit/entry.js
 @ multi ./node_modules/@nuxt/components/lib/installComponents.js ./.nuxt/nuxt-speedkit/entry.js

 FATAL  Nuxt build error                                                                                   3:29:53 PM

  at WebpackBundler.webpackCompile (node_modules/@nuxt/webpack/dist/webpack.js:1868:21)
  at processTicksAndRejections (internal/process/task_queues.js:95:5)
  at async WebpackBundler.build (node_modules/@nuxt/webpack/dist/webpack.js:1833:5)
  at async Builder.build (node_modules/@nuxt/builder/dist/builder.js:249:5)
  at async Object.run (node_modules/@nuxt/cli/dist/cli-build.js:99:7)
  at async NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-index.js:356:7)


   โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
   โ”‚                             โ”‚
   โ”‚   โœ– Nuxt Fatal Error        โ”‚
   โ”‚                             โ”‚
   โ”‚   Error: Nuxt build error   โ”‚
   โ”‚                             โ”‚
   โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Document how to add a plugin

Currently the README shows an example nuxt.config.js but the plugins array is empty. It would be good to expand on this example by adding an example of how to include a plugin.

Day JS in Nuxt guessing timezone using tz.guess() not a function

I'm using the @nuxtjs/dayjs module v1.4.1 in my Nuxt 2 project. I need to guess the user's timezone and set a datetime in their timezone. When I try to run my JS, I get an error telling me it's not a function, what am I missing?

// Day JS config
dayjs: {
  locales: ['en'],
  defaultLocale: 'en',
  plugins: [
    'utc',
    'timezone',
    'relativeTime',
    'advancedFormat',
    'localizedFormat',
    'customParseFormat'
  ]
},

Called like in a function:

this.$dayjs().tz.guess()

returns error:

this.$dayjs(...).tz.guess is not a function

Set defaultTimeZone from store?

Hello,

is it possible to set the default time zone globally out side from nuxt.config.js?

For example, in my config I have:

dayjs: {
        locales: ['en', 'de'],
        defaultLocale: 'en',
        defaultTimeZone: 'UTC',
        plugins: [
            'utc',
            'timezone'
        ]
    }

But on page load I want to override the default time zone with: this.$dayjs.tz.setDefault('Europe/Berlin').

Plugin list without extension not working anymore

In relation to this issue and comment, just adding e.g. 'utc' in the list of plugins doesn't work (anymore?) when building for production:

export default {
  locales: ['en'],
  defaultLocale: 'en',
  plugins: ['utc'],
};

This does seem to work:

export default {
  locales: ['en.js'],
  defaultLocale: 'en',
  plugins: ['utc.js'],
};

Edit: same for locales apparently

dayjs reverts to defaultLocale when rendered server side

So I've got the case that the global language changes depending on some api data:

async fetch() {
    const res = await this.$apollo.query({
      query: eventSeriesBySlug,
      variables: {
        'slug': this.$route.params.slug
      }
    });

    this.eventSeries = res.data.eventSeriesBySlug;

    // "en"
    this.locale = this.eventSeries.language.short;
    
    // i18n works fine and the page updates
    this.$i18n.setLocale(this.locale);

    // just updates and stays at the locale when rendered client side 
    this.$dayjs.locale(this.locale);
  }

The page / dayjs shows up for like 1 second in the right language but then switches back to whatever is standing in the nuxt config. (also watchable with {{ $dayjs.locale() }} "en" => "de" in my case)

dayjs: {
  locales: ['en', 'de'],
  defaultLocale: 'de',
  defaultTimeZone: 'Europe/Berlin',
  plugins: [
    'utc', // import 'dayjs/plugin/utc'
    'timezone' // import 'dayjs/plugin/timezone'
  ] // Your Day.js plugin
},

I'm not sure if this is a bug or a missing feature or if there's a workaround for this (but stackoverflow is suspicious quiet on this).

Edit: This just happens when rendered server side! Client side it's fine. But when doing a hard reload, the switch appears. Link: https://stackoverflow.com/questions/71557315/set-global-dayjs-locale-at-nuxt-ssr

Must be use TimeZone plugin?

( ใƒกใ‚คใƒณใ‚ณใƒณใƒˆใƒชใƒ“ใƒฅใƒผใ‚ฟใƒผใฎๆ–นใฏๆ—ฅๆœฌใฎๆ–นใงใ™ใŒไธ€ๅฟœ่‹ฑ่ชžใง้€ใ‚Šใพใ™ )

The Problem

Cannot read property 'setDefault' of undefined

image

Steps to Reproduce

  • Set Config
dayjs: {
    locales: ['en', 'ja'],
    defaultLocale: 'en',
    defaultTimeZone: 'Asia/Tokyo',
    plugins: ['utc'],
},

TS2345: Argument of type 'string' is not assignable to parameter of type

Hi there! I have bug with types when i'm try to use $dayjs inside of vuex mutations (example in photo below). when i'm assign value directly, without using of $dayjs module, error dissapears.
image

my tsconfig.json file includes:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": ["ESNext", "ESNext.AsyncIterable", "DOM", "DOM.Iterable"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "jsx": "preserve",
    "noEmit": true,
    "declaration": true,
    "noUnusedLocals": false,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "suppressImplicitAnyIndexErrors": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"]
    },
    "types": ["@nuxt/types", "@nuxtjs/dayjs", "@nuxtjs/auth-next", "@nuxtjs/axios", "@types/node", "nuxt-i18n", "@nuxt/image"]
  },
  "exclude": ["node_modules", ".nuxt", "dist", "stories"]
}

Have any ideas why it occurs?

Nuxt 3 Support

Hey ๐Ÿ‘‹ It looks like this module hasn't been updated for Nuxt 3. In an effort to improve the developer experience of modules, I've updated the module to clarify that it only supports Nuxt 2.

If Nuxt 3 support is added it will be moved to the https://github.com/nuxt-modules organisation.

Alternatives:

@potato4d Is Nuxt 3 support something you have planned? If not, perhaps we can deprecate this module.

Please let us know and thanks for your work!

Registering a local plugin

I have defined a plugin to add a function to the $dayjs() object:

// plugins/dayjs.js
export default (option, dayjsClass) => {
  dayjsClass.prototype.addWeekdays = function (numDays) {
    const direction = numDays < 0 ? -1 : 1
    let date = this
    while (numDays !== 0) {
      date = date.addDays(direction)
      if (date.day() !== 0 && date.day() !== 6) {
        numDays -= direction
      }
    }
    return date
  }
}

However, when using the plugins setting plugins: ['~/plugins/dayjs.js'] the module cannot be found because it looks within 'dayjs/plugin/~/plugins/dayjs`

Jest testing: TypeError: $dayjs is not a function

I'm trying to use dayjs in one of our tests but keep running into the following TypeError:

TypeError: $dayjs is not a function

It seems like dayjs isn't part of the context:

PublishDate.vue

setup(props) {
  const { $dayjs } = useContext()

  const formattedDate = ref(false)

  if (props.date && dateRegex.test(props.date)) {
    formattedDate.value = $dayjs(props.date).format(props.format)
  }

  return {
    formattedDate,
  }
}

PublisDate.spec.js

import { mount } from '@vue/test-utils'
import PublishDate from '@/components/Atom/PublishDate.vue'

describe('Badge', () => {
  test('Expect date to show "February 2021"', () => {
    const wrapper = mount(PublishDate, {
      propsData: {
        date: '2021-02-06T17:22+02:00',
      },
    })

    const PublishDateEl = wrapper.find('time')
    expect(PublishDateEl.element.textContent).toBe('February 2021')
  })
})

Stopped working in nuxt 3.0.0-rc.14

The plugin worked well until nuxt 3.0.0-rc.13 but starting from nuxt 3.0.0-rc.14 it fails as follows:

 Cannot read properties of undefined (reading 'dayjs')                                                                                                                                                                                 08:31:00

  at dayjsModule (node_modules/@nuxtjs/dayjs/lib/module.js:5:37)
  at installModule (node_modules/@nuxt/kit/dist/index.mjs:416:9)
  at async initNuxt (node_modules/nuxt/dist/index.mjs:1827:7)
  at async loadNuxt (node_modules/nuxt/dist/index.mjs:1859:5)
  at async loadNuxt (node_modules/@nuxt/kit/dist/index.mjs:493:19)
  at async Object.invoke (node_modules/nuxi/dist/chunks/prepare.mjs:30:18)
  at async _main (node_modules/nuxi/dist/cli.mjs:50:20)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.