How do I load bootstrap using npm?

Bootstrap is now a supported node package by the bootstrap guys.

https://www.npmjs.org/package/bootstrap

What this means is you can now require bootstrap in code. So.

npm install bootstrap --save

npm install jquery --save

foo.js

var $ = require('jquery');
window.$ = $;
require('bootstrap');

If you have some trouble to use require('jquery'), there is a more simple way to do it. Just redirect node modules folders (without using any require()).

app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

And on your views, just use simply :

<link href="/css/bootstrap.min.css" rel="stylesheet">
<script src="/js/jquery.js"></script>
<script src="/js/bootstrap.min.js"></script>

Assuming you want to install the latest version of Bootstrap 4, and that you are using node 10+ which uses npm at least 5.6+ (I used it for node v12.14.1 and npm 6.13.6, and it works properly):

npm install bootstrap
npm install jquery
npm install popper.js

Notice that you don't need to pass --save since after npm 5.0.0 installed modules are added as a dependency by default.

Now, assuming you have a file called index.html at the same directory of node_modules, you need to add the following to your head tag:

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">

You also need to add the following before </body>:

<!-- jQuery first, then Popper.js, then Bootstrap JS. -->
<script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Notice the comment: jQuery first, then Popper.js, then Bootstrap JS. This is important since Bootstrap depends upon JQuery and Popper.js.


You can try assigning it to global jquery property.

global.jQuery = require('jquery');