Bootstrap 4 with npm and webpack
Created by: IdanCo
I've been spending WAY too much time on adding bootstrap 4 with npm to a webpack project. In hope to save others the time, I thought i'll share the final recipe -
start by installing bootstrap in your project -
npm install bootstrap@4.0.0-alpha.6 --save
(notice bootstrap has two dependencies - jquery and tether. If you would rather have explicit versions of those two, you should install them as well)
import bootstrap's javascript through index.js -
import 'bootstrap';
(i'm assuming you're using es6, in case of es5, use require('bootstrap')
)
The previous line will only import the js part of bootstrap. for the styling part you have two options -
1. Precompiled SASS
Inside one of your sass files (index.scss for example) add this line -
@import "~bootstrap/scss/bootstrap.scss";
(notice the ~ (tilde) which points to the node modules folder) This mehtod is beneficial if you plan on using your own version of the wonderful _variables file bootstrap comes with. just make sure you import _variables before bootstrap. Also, now you can use all the cool mixins bootstrap has.
2. Compiled CSS only
If you're not planning on using the variables or the mixins, and prefer the precooked css file, simply add this line to index.js or any other js file -
import 'bootstrap/dist/css/bootstrap.css';
(btw - you can also import this way the sass file, but it's nicer to import it via another sass file as shown in pervious mehtod)
now comes the webpack part. for jquery and tether to be available as a global variable throughout the project, you'll have to add this to your webpack plugins sections -
new webpack.ProvidePlugin({ // inject ES5 modules as global vars
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Tether: 'tether'
})
The different jquery definition are meant to answer requirements of different libraries (for example angular looks for 'window.jQuery'). I'm assuming your webpack.config already has rules for scss and/or css.
And that's it! now you have bootstrap in your webpack project. Let me know if any further explanation is needed, and if anyone knows of a better way, please share.