#Dynamically import from public dir?

1 messages · Page 1 of 1 (latest)

rapid hatch
#

I want to do:

const pagefind = await import('/pagefind/pagefind.js');

But that doesn't work, however, this works:

        const pagefindScript = await fetch('/pagefind/pagefind.js').then(res => res.text());
        const blob = new Blob([pagefindScript], { type: 'text/javascript' });
        const url = URL.createObjectURL(blob);
        const pagefind = await import(/* @vite-ignore */ url);

Is this hacky workaround the only way to make this work?

static flame
#

You should be able to externalize and simply dynamically import.

#

pagefind.js would need to be in public/pagefind for it to be found and distributed.

rapid hatch
#

Because I tried but it still kept erroring

#

I tried: ["/pagefind/pagefind.js”]

rapid hatch
#

I've tried these now:

        rollupOptions: {
            external: [
                '/pagefind/pagefind.js',
                '/public/pagefind/pagefind.js',
                '/pagefind/pagefind',
                '/public/pagefind/pagefind'
            ]
        }
#

But I still get:

Internal server error: Cannot import non-asset file /pagefind/pagefind.js which is inside /public. JS/CSS files inside /public are copied as-is on build and can only be referenced via <script src> or <link href> in html. If you want to get the URL of that file, use /pagefind/pagefind.js?url instead.        
#

Looks like adding it to assetsInclude fixed it!

#

Not sure if that is the right approach but all of a sudden vite stops complaining and my code works as expected both during dev and build

rapid hatch
#

@static flame I think it was too late last night because what I thought was working actually didn't work, do you have any more tips on how to tell vite to stop analysing this import? I've tried nearly everything in every config option, it still marks it as unresolved (even though it will be resolved during runtime, vite just doesn't know that)