0

I'm from PHP background and using bootstrap framework for a while, currently working on a Node.js and express with routes project. I'm facing difficulty understanding how to call project assets (js, css, images etc) in views (index.html).

Used to include files like in (index.php)

<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>

I was trying similar approach in Node.js but it seems it was not straight forward while using routes.

I went through few SO1 to understand the concept but could not.

My index.js

var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

My index.html

<script src="../assets/jquery.min.js"></script>

The above approach did not work so I followed SO2 question

app.use('/assets', [
    express.static(__dirname + '/node_modules/jquery/dist/'),
    express.static(__dirname + '/node_modules/materialize-css/dist/'),
]);

<script src="/assets/jquery.min.js"></script> //in template

What's the better way to approach as I'll be having assets (jquery, bootstrap css, custom scripts etc).

1 Answers1

0

Moving forward in my project, I used the following approach to include all assets in views.

var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';


    router.use(function (req,res,next) {
        console.log("/" + req.method);
        next();
      });

      app.use('/assets', [
        express.static(__dirname + '/assets/'),
      ]);

      router.get("/",function(req,res){
        res.sendFile(path + "");
      });

      app.use("/",router);

      app.use("*",function(req,res){
        res.sendFile(path + "404.html");
      });

then by calling them in view files (in index.html) like

<script src="assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>