Skip to content

Duplicate module initialization with Swiper.use() and modules #8155

@mst-mkt

Description

@mst-mkt

Check that this is really a bug

  • I confirm

Reproduction link

https://codesandbox.io/p/sandbox/hungry-joji-p72lfq

Bug description

Module registered via Swiper.use() gets initialized twice when also specified in modules option.

Swiper.use([Navigation]);

new Swiper(".swiper", {
  modules: [Navigation],
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
});

As a result, this causes unexpected behavior, such as module effects being called twice. For example, if Navigation is registered twice, clicking on the navigation will cause it to move twice.

This is because Swiper.use([]) checks for duplicates, but new Swiper({ modules: [] }) does not.

  • Swiper.use([])

swiper/src/core/core.mjs

Lines 722 to 724 in 3a1777a

if (typeof mod === 'function' && modules.indexOf(mod) < 0) {
modules.push(mod);
}

  • new Swiper({ modules: [] })

swiper/src/core/core.mjs

Lines 95 to 97 in 3a1777a

if (params.modules && Array.isArray(params.modules)) {
swiper.modules.push(...params.modules);
}

Strictly speaking, this is not a bug, but rather bad user code.
However, I propose to eliminate duplication for the following reasons:

  • Duplication is already checked in Swiper.use([]).
  • The calls to Swiper.use([]) and new Swiper({ modules: [] }) are not necessarily close to each other, which can lead to unintentional duplication.
  • It is unlikely that modules would be intentionally registered multiple times.

Expected Behavior

Module initializes only once, regardless of registration method.

This prevents the module's operation from being called multiple times, even with code like the following:

Swiper.use([Navigation, Navigation]);

new Swiper(".swiper", {
  modules: [Navigation, Navigation],
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
});

Actual Behavior

Specifying the same module multiple times in the constructor registers multiple modules. This causes the module's operation (e.g., moving to the next slide in Navigation) to be called multiple times.

Swiper version

12.1.0

Platform/Target and Browser Versions

Arch Linux, Vivaldi (Chromium 142.0.7444.267)

Validations

  • Follow our Code of Conduct
  • Read the docs.
  • Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
  • Make sure this is a Swiper issue and not a framework-specific issue

Would you like to open a PR for this bug?

  • I'm willing to open a PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions