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.

3 Answers 3

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"/>
2
  • 6
    you may want to add a virtual path prefix for your static like: app.use("/bootstrap", express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
    – alexloehr
    Mar 19, 2019 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. Jul 16 at 9: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

2
  • Even better, use the output of require.resolve() as the path with your view engine. Mar 2, 2018 at 2:37
  • 4
    How is this supposed to work? node_modules folder is not visible for the browser in a standard express setup.
    – alexloehr
    Mar 19, 2019 at 14:33
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.