Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 58 ยท Quality

Bootstrap with Vite, Webpack and npm

Install Bootstrap 5.3 with npm and bundle it with Vite or webpack. Import only the Sass and JavaScript you need, avoid pitfalls and keep CSS small.

A CDN link is the fastest way to start with Bootstrap, but most real projects use a build tool. A build tool installs Bootstrap as a dependency, lets you customize it with Sass, includes only the parts you use, and produces small, cache-friendly files with hashed names. This is also how Bootstrap fits into frameworks and teams: a lockfile pins the exact version, and everyone builds the same output.

This lesson shows two setups, Vite and webpack, plus the shared ideas: what to install, how to import Sass and JavaScript selectively, how to deal with Sass warnings and how to keep the result small. The commands and configuration here run on your own machine with Node.js, so they appear as read-only code, not live examples.

The basics of npm and Sass are introduced in Installing Bootstrap and Customizing with Sass. This lesson builds on both. Version numbers below match Bootstrap 5.3.3 and may be newer in your project.

What you are building

flowchart LR
  A["src/main.js"] --> B["Bundler<br/>(Vite or webpack)"]
  C["src/styles/main.scss<br/>imports Bootstrap Sass"] --> B
  D["bootstrap JS modules"] --> B
  B --> E["dist/assets/app.[hash].css"]
  B --> F["dist/assets/app.[hash].js"]

The bundler compiles Sass, picks the JavaScript you use and writes optimized files.

Installing the packages

Start from an empty folder with Node.js installed:

Terminal
npm init -y
npm install bootstrap@5.3.3 @popperjs/core
npm install --save-dev sass
  • bootstrap contains the source Sass, the compiled dist/ files and the JavaScript modules.
  • @popperjs/core is Bootstrap's positioning engine for dropdowns, tooltips and popovers. It is a peer dependency: depending on your npm version it may not be installed for you, so add it explicitly. If you only use the CSS or components without popups, you can skip it.
  • sass (Dart Sass) compiles the SCSS. It is a development tool, not something your visitors download.

Setup 1: Vite

Vite is the quickest option: a dev server that updates in milliseconds and a production build powered by Rollup. Create a project with the vanilla template or add Vite to your own folder:

Terminal
npm install --save-dev vite

The folder structure:

TEXT
my-site/
  index.html
  package.json
  vite.config.js
  src/
    main.js
    scss/
      styles.scss

package.json scripts:

JSON
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  }
}

index.html loads one script, and Vite injects the CSS:

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Bootstrap site</title>
  </head>
  <body>
    <div class="container py-5">
      <h1>Hello, Bootstrap with Vite</h1>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#demo">Open modal</button>
    </div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js imports the styles and the JavaScript:

JavaScript
import "./scss/styles.scss";
import * as bootstrap from "bootstrap";   // everything; see below for selective imports

// Optional: expose it for inline scripts or the browser console
window.bootstrap = bootstrap;

src/scss/styles.scss imports Bootstrap's Sass:

SCSS
// Import everything
@import "bootstrap/scss/bootstrap";

Vite understands .scss files and resolves bootstrap/scss/... from node_modules, so no extra plugin is needed. Run npm run dev, open the printed URL, then npm run build to create the optimized dist/ folder.

Silencing Sass deprecation warnings

Newer versions of Dart Sass deprecate the @import rule that Bootstrap 5.3 still uses, and they warn about a few other things in Bootstrap's own files. The warnings come from inside node_modules, not from your code. You can quiet them in vite.config.js:

JavaScript
import { defineConfig } from "vite";

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        quietDeps: true,                          // hide warnings from node_modules
        silenceDeprecations: ["import", "global-builtin", "color-functions", "mixed-decls"],
      },
    },
  },
});

Hiding warnings is a trade-off. Bootstrap will move to the module system in a future major version, and until then these warnings are expected. Re-check them when you upgrade Bootstrap or Sass.

Setup 2: webpack

webpack is more configurable and still common in older or larger projects. It needs loaders to understand CSS and Sass:

Terminal
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin \
  style-loader css-loader sass-loader sass postcss-loader postcss autoprefixer \
  mini-css-extract-plugin

webpack.config.js:

JavaScript
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const production = process.env.NODE_ENV === "production";

module.exports = {
  mode: production ? "production" : "development",
  entry: "./src/main.js",
  output: {
    filename: "[name].[contenthash].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
  devServer: { static: "./dist", port: 8080, hot: true },
  plugins: [
    new HtmlWebpackPlugin({ template: "./index.html" }),
    new MiniCssExtractPlugin({ filename: "[name].[contenthash].css" }),
  ],
  module: {
    rules: [
      {
        test: /\.(scss)$/,
        use: [
          production ? MiniCssExtractPlugin.loader : "style-loader",
          "css-loader",
          { loader: "postcss-loader", options: { postcssOptions: { plugins: ["autoprefixer"] } } },
          { loader: "sass-loader", options: { sassOptions: { quietDeps: true } } },
        ],
      },
    ],
  },
};

Read the loader array from bottom to top: Sass compiles to CSS, PostCSS adds vendor prefixes, css-loader turns the CSS into a module, and then either style-loader injects it into the page (fast, for development) or MiniCssExtractPlugin writes a real CSS file (for production, so the browser can cache it and render without waiting for JavaScript).

The entry file src/main.js and the SCSS are identical to the Vite setup. Add "build": "NODE_ENV=production webpack" and "start": "webpack serve" to the scripts (on Windows use the cross-env package for the environment variable).

Customizing before importing

The point of building Bootstrap yourself is to change variables before the framework's CSS is generated. Put your overrides between Bootstrap's functions and the rest of the framework:

SCSS
// 1. Include functions first (so you can manipulate colors etc.)
@import "bootstrap/scss/functions";

// 2. Your variable overrides
$primary: #0f766e;
$font-family-sans-serif: "Inter", system-ui, sans-serif;
$enable-shadows: true;
$border-radius: 0.5rem;

// 3. Required Bootstrap files
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/utilities";

// 4. Layout and components you want
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/containers";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/card";
@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";

// 5. Generate the utility classes last
@import "bootstrap/scss/utilities/api";

Because Bootstrap's variables use !default, a value you set first wins. Every component you leave out disappears from the final CSS. If you add a utility or a map override ($theme-colors, $utilities), merge it after maps and before utilities/api, as described in The Utility API.

Do not delete files that other files depend on: functions, variables, variables-dark, maps, mixins and utilities must stay. If the build complains about an undefined variable or mixin, a required import is missing or in the wrong order.

Importing only the JavaScript you use

import * as bootstrap from "bootstrap" pulls in every plugin. If your site only uses modals and dropdowns, import them individually so the bundler can drop the rest:

JavaScript
import Modal from "bootstrap/js/dist/modal";
import Dropdown from "bootstrap/js/dist/dropdown";
import Collapse from "bootstrap/js/dist/collapse";

new Modal(document.getElementById("demo"));

Or import the names from the main entry and let tree-shaking do the work (works best in production mode):

JavaScript
import { Modal, Dropdown } from "bootstrap";

Notes:

  • Data attributes still work, but only for the plugins you imported. If you import Modal but not Collapse, data-bs-toggle="collapse" silently does nothing.
  • Plugins have dependencies: tooltips and popovers need Popper (@popperjs/core), and popovers also depend on the tooltip module. Dropdowns need Popper. Import errors like "Cannot find module '@popperjs/core'" mean you forgot it.
  • If you need bootstrap in inline <script> blocks or the console, assign it to window as in main.js above. Modules are not global by default.
  • Use data-bs-* attributes through the bundle exactly as in the CDN version: the markup does not change. See Bootstrap JavaScript Plugins.

Keeping the output small

  1. Import selectively. A full Bootstrap CSS build is roughly 30 KB compressed; leaving out components you do not use can trim it considerably.
  2. Remove unused CSS with a tool such as PurgeCSS or Lightning CSS minification, configured with a safelist for classes added at runtime (show, collapsing, modal-backdrop, fade, active). Test thoroughly: purging is aggressive and can remove classes you add only from JavaScript.
  3. Use the Utility API to limit generated utilities: set unused utilities to false or reduce their value maps (see The Utility API).
  4. Compress and cache. Serve with Brotli or gzip, use hashed file names and long cache lifetimes.
  5. Measure with the production build's size report, not the dev server.

More on this in Performance and Best Practices.

Common problems

Symptom Likely cause
Undefined variable: $... Bootstrap files imported in the wrong order, or variables imported before your overrides
Undefined mixin mixins not imported
Dropdowns or tooltips do not position @popperjs/core missing, or you used bootstrap.js without Popper
data-bs-toggle does nothing The plugin was not imported (tree-shaking) or the JavaScript loaded before the markup
Deprecation warnings flood the terminal Dart Sass version is newer than Bootstrap's import-based Sass. Use quietDeps and silenceDeprecations.
bootstrap is not defined in an inline script Modules are not global: window.bootstrap = bootstrap
Icons or fonts missing Bootstrap Icons is a separate package (bootstrap-icons), with its own CSS and font files
Styles missing after the build Forgot to import the SCSS file in main.js

Which tool should you choose?

  • Vite for new projects, quick feedback and simple configuration.
  • webpack when you maintain an existing webpack setup or need its plugin ecosystem.
  • A framework's build (Next.js, Nuxt, Angular CLI, Laravel with Vite) when you already use one: install bootstrap and sass, import the SCSS from the framework's entry file, and apply the same rules. For component libraries, see Using Bootstrap with React and Vue.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where in your SCSS must your variable overrides (such as $primary) go?

    Bootstrap's variables use !default, so a value defined before they are imported wins. Functions come first because overrides may call them.
  2. 2. Why add @popperjs/core when installing Bootstrap with npm?

    Popper positions floating elements. npm may not install peer dependencies automatically, so add it if you use those plugins.
  3. 3. What is the effect of importing only Modal and Dropdown from bootstrap?

    Unimported plugins are not in the bundle, so their data attributes have no effect.
  4. 4. What does the order of webpack loaders in the use array mean?

    webpack applies loaders right to left or bottom to top, which is why sass-loader comes last in the array.
  5. 5. Why use MiniCssExtractPlugin in production instead of style-loader?

    style-loader injects CSS with JavaScript at runtime. A real file is cached and loaded in parallel.

Summary

  • Install bootstrap, @popperjs/core (for popups) and sass, then import SCSS and JavaScript from your entry file.
  • Vite needs almost no configuration; webpack needs loaders (sass-loader, css-loader, PostCSS) and an extract plugin for production.
  • Override variables after functions and before variables, import only the components you need, and finish with utilities/api.
  • Import individual JS plugins to enable tree-shaking, and remember that unimported plugins do nothing.
  • Quiet known Sass deprecation warnings with quietDeps and silenceDeprecations, and measure the production output.

Next lesson: Migrating from Bootstrap 4 and Using Icons, where you move older projects forward and add icons.