Skip to content

The above dynamic import cannot be analyzed by Vite. #67

@kenlyon

Description

@kenlyon

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:

  1. I added the import:
import dynamicImport from "vite-plugin-dynamic-import";
  1. 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;
        },
    }),
    ...
],
  1. 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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions