Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic Imports & Vite #7

Open
mattbloomfield opened this issue Oct 16, 2024 · 4 comments
Open

Dynamic Imports & Vite #7

mattbloomfield opened this issue Oct 16, 2024 · 4 comments

Comments

@mattbloomfield
Copy link

Hi all, I know you call out in the docs that Vite does not support Dynamic Imports due to limitations with rollup... but I was curious if anything has changed over the past few years or if anyone has found a workaround?

@13twelve
Copy link
Member

13twelve commented Oct 28, 2024

@mattbloomfield I looked into this again a couple of months ago using vite-plugin/vite-plugin-dynamic-import and initially thought I'd found a way of doing it, only to find that it only works in development builds but not production builds.

It is something we're very keen to get working. I'll leave this issue open and update when we find a way.

@13twelve
Copy link
Member

Vite 6 released in late November - we'll be looking at dynamic imports with Vite 6 shortly

@mattbloomfield
Copy link
Author

Sweet!

@mrdoinel
Copy link
Collaborator

mrdoinel commented Jan 8, 2025

Another way to handle this issue is to lazyload only the big libraries from your behaviors.
So all behaviors are bundled into the production build but third party packages are loaded only if necessary. For example if you have a behavior for a carousel that is only on a certain page you could load Swiper or any other library only if the carousel is present.

This way of importing (with no variables in the names) is working fine with Vite

const Carousel = createBehavior(
    'Carousel',
    {
        async initCarousel() {
            if (this.swiper) return

            // import swiper and modules only when initializing the carousel
            const { Swiper } = await import('swiper')
            const { A11y, Autoplay, EffectFade, Navigation, Pagination } =
                await import('swiper/modules')

            // init swiper
            this.swiper = new Swiper(this.$node, this.opts)
        }
    },
    {
        init() {
            this.swiper = null
            // options
            this.opts = {
                navigation: {
                    nextEl: '.swiper-next-btn',
                    prevEl: '.swiper-prev-btn'
                }
            }
        },
        enabled() {
            void this.initCarousel()
        },
        disabled() {
            this.swiper?.destroy()
            this.swiper = null
        }
    }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants