How to include Bootstrap in your project with Webpack
Updated on
Now that Bootstrap 4 has arrived, I thought I’d share an example configuration to include Bootstrap as part of the Webpack bundling process. This allows you to override the built-in variables and integrate Bootstrap components into your Webpack bundle.
Create the following directory structure for your project, separating the “source” code /src from our bundled “distribution” code /dist.
Project structure
Installing Bootstrap
Use the following command to install Bootstrap and its peer dependencies, jQuery and Popper:
If you choose to import Bootstrap’s JavaScript plugins individually as needed, you must also install exports-loader.
You’ll need to install the required loaders and postcss plugins for compiling and bundling Bootstrap precompiled Sass files.
Webpack configuration file
Create a webpack configuration file. The example configuration file included below assumes you’ll be using the Boostrap Sass source files as part of your project’s bundling process.
Project structure
webpack.config.js
Importing Bootstrap JavaScript
Import Bootstrap’s JavaScript by adding this line to your app’s entry point /src/app.js:
Alternatively, you may import plugins individually as needed:
Importing Bootstrap Sass
When importing Bootstrap’s Sass source files you can include all of Bootstrap, or pick only the parts you need. Update your project’s directory structure and create a new file /src/scss/app.scss.
Project structure
Import all of Bootstrap’s Sass by adding this line to app.scss
app.scss – Include all of Bootstrap
Alternatively, you may import parts of Boostrap individually as needed. Note that Bootstrap’s functions, variables and mixins are required. See the boostrap.scss file for the full import stack.
app.scss – Include parts of Bootstrap
Finally, include Bootstrap’s Sass in your bundle by adding this line to your app’s entry point /src/app.js:
Bundling with Webpack
Edit your package.json file to add a npm script to run the webpack command.
package.json
You may now use the npm run build command to build your bundle with Webpack.
To test your bundle, create a new file /dist/index.html:
The components that were included in your bundle are available after the bundle.js script has loaded.