22

I 'm a beginner of Node.js development, Now I try to use bootstrap framework in my first Express web app.

I use

npm install bootstrap

to download the files,and it seems that npm puts them in my node_modules folder.

My question is how can I refer to the bootstrap files in my views in express?

I know a typical way is copying the bootstrap file into the public folder. So my html files can find them. But I don't think this is a good idea.

Thank you.

Keyu Lin
  • 3,669
  • 3
  • 12
  • 8

3 Answers3

50

You need to use in your server.js:

app.use(express.static(__dirname + '/node_modules/bootstrap/dist'));

to define a static resourse and then use:

<script language="javascript" src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
Victor Behar
  • 740
  • 6
  • 9
  • 6
    you may want to add a [virtual path prefix](https://expressjs.com/en/starter/static-files.html) for your static like: `app.use("/bootstrap", express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));` – alexloehr Mar 19 '19 at 14:39
  • I found a similar question. In which the solution is explained better by @augusto-goncalves. His solution works for me. It is similar to the solution above but more elaborated and clears confusion. – Akarsh SEGGEMU Jul 16 '23 at 09:34
3

You have to reference it in the <script> and <link> tags in the header or at the bottom of your main script.

If you're using express, you're probably using templating. To use it in your header part or in your main template (depending on how you've managed your views) like :

<script language="javascript" src="node_modules/bootstrap/.../bootstrap.min.js"></script>

and

<link rel="stylesheet" href="node_modules/bootstrap/.../bootstrap.min.css"/>

This works only if you didn't moved your files with a gulp or a grunt task

Sébastien
  • 11,860
  • 11
  • 58
  • 78
mfrachet
  • 8,772
  • 17
  • 55
  • 110
1

There's also a way to transpile scss in express using node sass middleware, for example https://github.com/sass/node-sass-middleware.

That way you can override bootstrap scss. You can do the same for JS with webpack: transpile client-side js and then include the bundle.js in your frontend.

morpheus
  • 11
  • 1