Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get locale dynamically from dayjs https://www.npmjs.com/package/dayjs?

Tags:

npm

locale

dayjs

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?

like image 483
mayank goyal Avatar asked Jan 06 '20 09:01

mayank goyal


3 Answers

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))
}
like image 130
gernsdorfer Avatar answered Oct 20 '22 03:10

gernsdorfer


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

like image 29
Roy Hershkovitz Avatar answered Oct 20 '22 02:10

Roy Hershkovitz


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' })
like image 42
Dipten Avatar answered Oct 20 '22 01:10

Dipten