How to dynamically import json

Example:
import countries from 'i18n-iso-countries';
countries.registerLocale(await import(`i18n-iso-countries/langs/${"en"}.json`));
return json(countries.getNames("en"));
import countries from 'i18n-iso-countries';
countries.registerLocale(await import(`i18n-iso-countries/langs/${"en"}.json`));
return json(countries.getNames("en"));
${"en"} will break it - but if i put 'en' directly it works. are dynamic import not supported?
7 Replies
kian
kian12mo ago
You need to tell Wrangler that it should be bundling them, otherwise they wouldn't be available at runtime
kian
kian12mo ago
Configuration · Cloudflare Workers docs
Wrangler optionally uses a wrangler.toml configuration file to customize the development and publishing setup for a Worker.
identity
identity12mo ago
thanks @kiannh - this makes total sense. do you know how to provide bundling rules to the wrangler pages command? I am asking since I am using Cloudflare Page Functions which use workers implicitly and it doesn't seem to read wrangler files
kian
kian12mo ago
I don't think you can with Pages
identity
identity12mo ago
good to know - you think i need to convert from pages to using workers directly to get it to work?
kian
kian12mo ago
You could probably add these to a 'public' folder of sorts (https://github.com/michaelwittig/node-i18n-iso-countries/tree/master/langs) and do env.ASSETS.fetch(pathhere) I didn't realise these were from an NPM package rather than your own JSON files - so the bundling rules probably wouldn't do a whole lot either but I guess you could make the rule for ./node_modules/i18n-iso-countries/...
identity
identity12mo ago
thanks @kiannh I appreciate your help. it's unfortunate that there's no easy way to have this work. env.ASSETS.fetch appears to require to move to the more advanced/custom _worker.js method.