How to use Bootstrap5 with Vite and Nuxt3?

Viewed 1074

Tailwind makes it easy to use its CSS in projects set up with Vite as you can see here.

However, Bootstrap 5 only has information available for using with Webpack.

I can not find anything about how to set Bootstrap 5 CSS with Vite. Does anyone have any tips on how to successfully and optimally set up Bootstrap 5 with Vite? I am using Nuxt3 but it should not matter which framework one uses.

1 Answers

Variant 1. Add it to nuxt.config.ts

import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
  app: {
    head: {
      link: [
        { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css', integrity: 'sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor', crossorigin: 'anonymous' }
      ],
      script: [
        { src: 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js', integrity: 'sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2', crossorigin: 'anonymous' }
      ]
    }
  }
})

Downside: needs manual version control, you can't use SASS features.

Variant 2.

  1. Install bootstrap alongside @popperjs/core
yarn add bootstrap @popperjs/core
  1. Create plugins/useBootstrap.client.ts file
import bootstrap from 'bootstrap/dist/js/bootstrap.bundle'

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.provide('bootstrap', bootstrap)
})

No need to import it manually, since Nuxt3 will do it for you. Bootstrap JS should be available in your components/pages through

const { $bootstrap } = useNuxtApp()
  1. Create assets/styles/main.scss file
@import 'bootstrap/scss/bootstrap';
  1. Add it to nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  css: ['~/assets/styles/main.scss']
})
Related