When I use like dayjs(date).locale('te').format('YYYY MMM DD')
, then I get Month value in english. For working with locale, I have to import locale.
import * as locale from 'dayjs/locale/te';
The problem is that I don't see a way to dynamically import a locale. I don't have access to nodejs require() function. I have react based application. How to mitigate this issue?
A workaround for dynamic Imports without errors:
const locales = {
de: () => import('dayjs/locale/de'),
en: () => import('dayjs/locale/en'),
}
function loadLocale (language) {
locales[language]().then(() => dayjs.locale(language))
}
You can use import as import expression and dynamically import whatever you want. for example:
import dayjs from "dayjs";
import localeData from "dayjs/plugin/localeData";
dayjs.extend(localeData);
const LOCALE = "de";
import(`dayjs/locale/${LOCALE}`)
.then(() => {
dayjs.locale(LOCALE);
console.log(dayjs.weekdays());
});
You can see a working example in this codesandbox.
for more information on dynamic imports I suggest you to read https://javascript.info/modules-dynamic-imports
You need to first import needed locale files as below
import 'dayjs/locale/te'
import 'dayjs/locale/en'
Then you can switch between locals dynamically as below operations
dayjs().locale('en').format()
dayjs('2018-4-28', { locale: 'te' })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With