I have some code that dynamically loads the locale for use with the date-fns library:
const localeObj = await import(`date-fns/locale/${locale}/index.js`
I was able to use vite-plugin-dynamic-import to get this to work in the build by making the following changes to my vite.config.ts file:
- I added the import:
import dynamicImport from "vite-plugin-dynamic-import";
- I added configuration for the plugin to the
plugins array:
plugins: [
dynamicImport({
loose: true,
onFiles: (files: string[], id: string) => {
if (id.includes("/MyFileName.tsx")) { // The file that contains the dynamic import.
// I do not want to bundle anything in "_lib" folders.
files = files.filter((file) => file.indexOf("/_lib/") === -1);
}
return files;
},
}),
...
],
- This was more of a cosmetic step. I added the following to name the relevant chunks with a
date-fns- prefix.
build: {
rollupOptions: {
output: {
chunkFileNames: (chunkInfo: PreRenderedChunk) => {
if (
chunkInfo.moduleIds.some((moduleId: string) =>
moduleId.includes("date-fns")
)
) {
return "date-fns-[hash].js";
}
return "[name]-[hash].js";
},
},
},
},
This works as intended when I perform vite build which is great! The problem is that when I try to start the project on my development workstation, it does not work.
When I perform yarn vite, the output shows my dynamic import followed by this message:
The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.
I can add a /* @vite-ignore */ comment to suppress the warning, but the dynamic import does not work.
It produces this error:
TypeError: The specifier “date-fns/locale/az/index.js” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.
Is there a way to get vite-plugin-dynamic-import to work when using vite to run the dev server?
I have some code that dynamically loads the locale for use with the
date-fnslibrary:I was able to use
vite-plugin-dynamic-importto get this to work in the build by making the following changes to myvite.config.tsfile:pluginsarray:date-fns-prefix.This works as intended when I perform
vite buildwhich is great! The problem is that when I try to start the project on my development workstation, it does not work.When I perform
yarn vite, the output shows my dynamic import followed by this message:I can add a
/* @vite-ignore */comment to suppress the warning, but the dynamic import does not work.It produces this error:
Is there a way to get
vite-plugin-dynamic-importto work when usingviteto run the dev server?