#Dynamic import files

1 messages · Page 1 of 1 (latest)

tawny gyro
#

I have some json files (svg) on the public folder that I used to load dynamically in NextJs.

  import(`/jsons/vowels/${src}-ton.json`).then(setDataM);
  import(`/jsons/vowels/${src}-lips.json`).then(setDataF);
}, [src]);

In Remix it fails:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.
Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:8788/jsons/vowels/eh-lips.json

Isn't is possible to load files this way? It has to be via loader?

lime briar
#

This is most likely because Next uses webpack which does magic things with your dynamic imports to apply webpack loaders so you can import json, while Remix is not doing that so the import reach the browser and you can't import json files, only JS files, on a browser

#

I recommend you to instead read them server-side in the route loader, and then send them to the UI

tawny gyro
#

And how do I read local files in the public folder ? using fs in the loader?

lime briar
#

yes

tawny gyro
#

BTW, I'm using CF Workers, and I've realized fs isn't available in workers, right
What other options do I have? to store them in KV or R2?

lime briar
#

what are those files? are they really dynamic? maybe you could import them statically?

dim mauve
#

The problem here is the dynamic string interpolation inside import()

#

If the string is static it can be imported dynamically

#

At least that is the case with JS, I haven't actually done this with JSON

#

Those files are never actually dynamic, you can always do the import(string) bit statically eg. At the top level of your module:

const importFooVowels = () => import("/JSON/vowels/foo-ton.json");

const importBarVowels = () => import("/JSON/vowels/bar-ton.json");

#

It's unfortunate that this has to be done tbh, but it's a limitation in esbuild right now 🫤

tawny gyro
#

The files are svg files converted to json to be used by Lottie. Yes, the string is dynamic because it changes based on the props I pass to the component

tawny gyro
#

I think I'll try to load it via loader and R2...

dim mauve
#

Did you try importing relative to the current script?

#

And is that error at build time?

dim mauve
#

Consider KV for lower latency 👍

tawny gyro
#

Importing relative to the current script, it tries to import a js file:

() => import("/build/_shared/iy-ton-OAELNVHA.js")
dim mauve
#

Damn

#

The other thing you can do is fetch() from your public folder