nuxt-community / dayjs-module Goto Github PK
View Code? Open in Web Editor NEWDay.js module for your Nuxt 2 project.
Home Page: https://www.npmjs.com/package/@nuxtjs/dayjs
License: MIT License
Day.js module for your Nuxt 2 project.
Home Page: https://www.npmjs.com/package/@nuxtjs/dayjs
License: MIT License
Evening!
Can you enable dayjs
plugins (e.g. customParseFormat
) in the current implementation of the module?
Thanks in advance.
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
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.
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?)
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.
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.
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!
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.
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.
Can you update dayjs to latest version (1.10.4)?
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
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
all-contributors-cli
, typescript
)@nuxt/types
, nuxt
)@types/jest
, jest
, ts-jest
).circleci/config.yml
circleci/node 16.13.1-browsers
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
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!
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.
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
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
Any plans to include filters out of the box? Would a PR including some be accepted?
It seems it's not used, but referenced in package.json
I would like to change the format for relativeTime: https://day.js.org/docs/en/customization/relative-time. But i dont know how implement in nuxtconfig
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
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.
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.
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?
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')
.
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
I'm getting this console error when I use this.$dayjs.weekdays() even though i added the corresponding dayjs type into de tsconfig like so:
"types": [
"@types/node",
"@nuxt/types",
"@nuxtjs/dayjs",
"@nuxtjs/axios",
"./types/"
]
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?
How to parse from specific locale ? For example parsing from Indonesian locale "20 Mei 2022 00:00"
Hello,
when I use fetch for creating a dayjs object, I can not access it later in a component.
Here is a example: https://codesandbox.io/s/withered-wildflower-kno4d
Is there a way to use dayjs object on client side, when it was created on server side?
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`
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>)
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')
})
})
For this module to be used with vite
we'll need to convert the dynamic require
calls to imports.
See nuxt/vite#120
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 |
plugins: [
'~/plugins/dayjs.js',
],
modules: [
'@nuxtjs/dayjs'
],
dayjs: {
locales: ['en', 'de', 'la'], // la for Latin language
defaultLocale: 'de',
plugins: [
'utc',
'timezone',
'customParseFormat',
'advancedFormat',
],
},
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'
}
})
}
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 โ
โ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
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.
How can I use $dayjs
with a Vue.mixin
?
yarn add @nuxtjs/dayjs
'@nuxtjs/dayjs'
to modules: []
in nuxt.config.js
dayjs.js
in /plugins
{src: '~/plugins/dayjs'},
to plugins: []
in nuxt.config.js
import Vue from 'vue'
Vue.mixin({
methods: {
format_date: function (date) {
return this.$dayjs(date).format('L');
}
}
})
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.