How to import a single Bootstrap 5 JS component in a Nuxt 3 page component?

Viewed 99

Is it possible to import just a single Bootstrap 5 component into a Nuxt 3 app's component? In this specific case, I want to use the Dropdown component from Bootstrap 5. That requires JavaScript.

I tried to do it like so:

app.vue:

<template>
  <div class="container mt-4">
    <ClientOnly><Dropdown /></ClientOnly>
  </div>
</template>

Dropdown.vue:

<template>
  <div class="dropdown">
    <button
      class="btn btn-secondary dropdown-toggle"
      type="button"
      id="dropdownMenuButton1"
      data-bs-toggle="dropdown"
      aria-expanded="false"
    >
      Dropdown button
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
      <li><a class="dropdown-item" href="#">Action</a></li>
      <li><a class="dropdown-item" href="#">Another action</a></li>
      <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
  </div>
</template>

<script setup>
import dropdown from 'bootstrap/js/dist/dropdown'; //<--- how do I correctly import dropdown??
</script>

That did not work. Anyone have any ideas on how to "tree shake" Bootstrap JS and just import the needed components in a local component?

1 Answers

On the download page you find this paragraph:

Source files

Compile Bootstrap with your own asset pipeline by downloading our source Sass, JavaScript, and documentation files. This option requires some additional tooling:

Should you require our full set of build tools, they are included for developing Bootstrap and its docs, but they’re likely unsuitable for your own purposes.

So likely you could reduce it a lot but for some basic files it might hard to exclude them or even to decide if they should be excluded.

Anyway, bootstrap sass is quite modular and it seems to be possible to create an own compilation with only one component. Beside that I don't think that there exists another option and you had to use your own compilation.

Related