Dynamic locale import with Vite #3432
Unanswered
jbaldassari
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've recently been working on migrating a project from Create React App to Vite, and one place where I got stuck was the dynamic import of
date-fns
locales. I finally found a couple of solutions, and since I haven't seen these anywhere else I thought I'd just post them here in case it helps anyone else.Just for reference, this is how I was doing the imports with Webpack:
Here
localeCode
is a variable containing the locale string, e.g.en-US
,es
, etc. This value is either automatically detected by a module or configured by the user. For that reason I can't just statically import a bunch of locales. I really want it to support loading arbitrary locales at runtime without bundling them all into the main chunk.This was all working with CRA/Webpack, but after switching to Vite the dynamic imports were failing to load. I don't fully understand all the reasons why yet, but it seems like support for dynamic imports (particularly with variable components) is much more limited in Vite than Webpack. The first way I tried to get it working, which wasn't successful, was to dynamically load the locale directly out of
node_modules
:This causes Vite to blow up with an error like:
I guess this happens because the code inside the locale module uses
require
, which isn't supported in Vite. There are a number of workarounds for this issue documented here, but they all seem fairly complex and brittle.Eventually I figured out a couple of ways to make it work, but both of them have some serious drawbacks.
Solution 1: Import the individual locale via https://esm.sh or https://www.jsdelivr.com
Instead of bundling the locales, we just fetch them dynamically at runtime from https://esm.sh or https://cdn.jsdelivr.net which are free services that cache node modules for this purpose.
Pros:
Cons:
https
module (e.g. https://github.com/davidmyersdev/vite-plugin-node-polyfills)Solution 2: Importing all locales dynamically
This solution involves loading a single default locale via a static import, and then if the locale changes to something that is not the default, we load all locales and then extract the requested locale. It would look something like this:
Pros:
Cons:
So far these are the only solutions I've found that work with Vite. I'm interested in hearing if anyone else has found a better way to dynamically import individual locales.
Beta Was this translation helpful? Give feedback.
All reactions