What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings.

AcceptLanguageList = CultureInfo.CurrentUICulture.Name

In my TypeScript code, I need to utilize dayjs and dynamically import 'dayjs/locale/${language}' where the language is fetched from AcceptLanguageList mentioned above.

import React, { useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import localeData from 'dayjs/plugin/localeData';

dayjs.extend(localeData);
var lang = navigator.languages != null ? navigator.languages[0] : navigator.language;
lang = lang.toLowerCase();
import(`dayjs/locale/${lang}`).then(
        () => {
            dayjs.locale(lang);
            setAdapterLocale(lang);
        });

The issue arises when running this code in the browser. Importing 'dayjs/locale/fr-ca', for instance, works fine but if 'fr-ca' comes from CefSharp, the import fails with the following error:

Uncaught (in promise) TypeError: Failed to resolve module specifier 'dayjs/locale/fr-ca'

I would greatly appreciate any assistance on this matter.

Answer №1

To ensure a dynamic import path works effectively, you must first specify all possible paths that may be needed. Failure to do so will result in the bundler being unsure about which files to include.

Simply add import('dayjs/locale/fr-ca') anywhere within your code, and the bundler will automatically include it during the app's build process for web browsers.

If a locale matching the user's language is missing, an error will still occur. To handle this situation gracefully, consider addressing it as follows:

import(`dayjs/locale/${lang}`).then(
        () => {
            dayjs.locale(lang);
            setAdapterLocale(lang);
        },
        () => { // handle import failure
            // possibly fallback to English
            dayjs.locale('en');
            setAdapterLocale('en');
        });

Answer №2

After some investigation, I was able to solve the issue. The problem stemmed from the package build for the .net app, which utilized rollup (unlike when running in a browser). To address this, rollup requires specific configuration to support dynamic imports: https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Ways to navigate to a new page using jQuery Mobile

As a newcomer to jquery mobile, I am still learning how ajax handles page transitions, and I suspect the issue may be related to that. In my jqm / phonegap app, I have set up multiple pages. The homepage checks if the user is logged in by retrieving membe ...

Displaying a component following data retrieval in Vue.js

I am currently working on consuming an API using axios. Here is the code I have so far: <select> <option v-for="value in values"> value.name </option> </select> // js data(){ values: [], }, create ...

Transferring information from the main function to getServerSideProps

I've been facing challenges while trying to pass data from a function component to the getServerSideProps method in Next.js. As a beginner in learning Next.js, I am struggling to understand this concept. My approach involves using context from _app, b ...

Having trouble getting JSON data to display in CanvasJS

I am trying to retrieve JSON data using Ajax with this code. It works fine when fetching data from the original source, but it's not working with my own JSON data. What could I be missing? Any help would be greatly appreciated. Thank you. $(document) ...

Can JavaScript be executed from the console while navigating between pages?

I am facing a challenge that I can't find any solutions for online or elsewhere. The task at hand seems straightforward. I am using the Chrome console and attempting to run Javascript code to navigate between pages with pauses in between. It feels lik ...

I'm encountering a strange issue where Node JS is mistakenly claiming that the method doesn't exist, even though

Ah, it seems I've encountered an error in my test project. The issue lies with Node JS not being able to locate the getStr function within the Another object. Allow me to share the code with you: test.js var Another = require('./another.js&apo ...

Attempting to insert a line break tag within the text using React

Having trouble inserting line breaks in text using React. Can anyone guide me on how to achieve this? I've attempted adding the br tag, but it is displaying as in the browser. Here's a snippet of my code. Appreciate any help or advice. let sp ...

Is there a way to utilize ng-if within a button to reveal the remaining portion of a form using TypeScript?

Can anyone help me figure out how to make the rest of my form appear when I click on a button? I think I need to use Ng-if or something similar. Here is the code for the button: <button type = "button" class="btn btn-outline-primary" > Données du ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Issue persists: Ajax functionality remains nonfunctional, prompting the need for

My goal is to use the post input, and upon hitting enter, I want to dynamically replace <div id="mainPagePosts"></div> with new data without causing a page refresh. However, even after submitting the post, the page still refreshes, although I d ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

Inquiry regarding Typescript's array of types

While researching how to declare arrays of types online, I came across the following example: arrayVar: Array<Type> Seems simple enough, so I attempted to declare my variable like this: transactions: Transactions = { total : 0, list: Array<Transa ...

When I click the back button on my mouse in React, it returns JSON data instead of HTML and CSS

I am working on a web application with two pages: a menu and orders. When I navigate from the orders page to the menu page and click the back button, I receive JSON data instead of the HTML page. The data loads correctly, but the page does not display the ...

Sending an onclick event to a child class through React and TypeScript

I'm currently working through the Facebook React tutorial with Typescript for the first time. I need to pass an onClick event to the 'Square' component, which is implemented using Typescript and interfaces for state and props. How can I mod ...

Monitoring and recording every server-side interaction within the AngularJS user interface

Is there a way to efficiently display all server side REST actions on the angular js UI of my application? For example, how can I immediately show a message on the GUI when a user is created or when an action fails? I currently store all such actions in a ...

What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

Navigating an Array in Typescript

Angular is linked to node.js, which interacts with mongodb to fetch data successfully. However, I am now faced with the challenge of mapping variables in my typescript component to the backend node.js. When viewing the data structure in the browser consol ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...