7

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?

mayank goyal
  • 87
  • 1
  • 1
  • 6

5 Answers5

7

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))
}
gernsdorfer
  • 71
  • 1
  • 2
6

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

  • 3
    Neat solution! But it might be better to add `.js` into the import statement as it might provoke compile errors if used in webpack without typescript configuration: import(`dayjs/locale/${LOCALE}.js`) – Hexodus Sep 23 '21 at 15:00
  • @Hexodus for me the `.js` was the crucial bit for my typescript app. – munsu Jul 18 '23 at 08:30
2

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' })
Dipten
  • 1,031
  • 8
  • 16
0

One thing you could do if you don't mind adding a promise there is to dynamically import the locale you need. The code would look like this:

const convertToLocale = (date, locale) => {
  return import(`dayjs/locale/${locale}`)
    .then(() => dayjs(date).locale(locale));
}

This will load all locale files as the import you mentioned would without the need to add the import statements by hand.

0

Try this code.

const language = {
    en: import('dayjs/locale/en'),
    te: import('dayjs/locale/te')
}

language['te'].then(lng => { console.log((dayjs(new Date()).locale(lng.name).format('YYYY MMMM DD')))})
Deep
  • 525
  • 3
  • 8