Bootstrap and npm
The official guide for how to build a starter project with Bootstrap’s CSS and JavaScript in your project using just npm.
Want to skip to the end? Download the source code and working demo for this guide from the twbs/examples repository. You can also open the example in StackBlitz.
Setup
We’re building a npm project with Bootstrap from scratch, so there are some prerequisites and upfront steps before we get started. This guide requires you to have Node.js installed and some familiarity with the terminal.
-
Create a project folder and set up npm. We'll create the
my-projectfolder and initialize npm with the-yargument to avoid it asking us all the interactive questions.mkdir my-project && cd my-project npm init -y -
Install Bootstrap. Now we can install Bootstrap. We'll also install Popper since our dropdowns, popovers, and tooltips depend on it for their positioning. If you don’t plan on using those components, you can omit Popper here.
npm i --save bootstrap @popperjs/core -
Install additional dependencies. In addition to Vite and Bootstrap, we have some dependencies used to import and bundle Bootstrap’s CSS. Sass compiles our source
.scssfiles into CSS and then Autoprefixer and PostCSS handle browser compatibility. We install thepostcss-clipackage so we can work with PostCSS via CLI.npm i --save-dev autoprefixer postcss postcss-cli sass -
Install local development tools. Lastly, to make life a little easier, we recommend installing some dev tools to make running local servers with hot refresh (where changes you make are reflected in the browser automatically) and add some code quality checks.
We use
nodemonto watch files for changes,npm-run-allto run multiple npm scripts at a time,sirv-clito run a local server, andstylelintto format CSS like Bootstrap does for consistency.npm i --save-dev nodemon npm-run-all sirv-cli stylelint stylelint-config-twbs-bootstrap
Now that we have all the necessary dependencies installed, we can get to work creating the project files and importing Bootstrap.
Project structure
We’ve already created the my-project folder and initialized npm. Now we'll also create our src folder, stylesheet, and JavaScript file to round out the project structure. Run the following from my-project, or manually create the folder and file structure shown below.
mkdir {css,js,scss}
touch index.html js/main.js scss/styles.scss .stylelintrc.jsonWhen you’re done, your project should look like this:
my-project/
├── css/
├── js/
│ └── main.js
├── scss/
│ └── styles.scss
├── index.html
├── package-lock.json
└── package.jsonAt this point, everything is in the right place, but we’ll need to add some npm scripts to use our dependencies and compile the CSS.
Configure
- npm scripts
- stylelint configuration
Import Bootstrap
See something wrong or out of date here? Please open an issue on GitHub. Need help troubleshooting? Search or start a discussion on GitHub.