skip to Main Content

I’ve a views folder which I made static using app.use(express.static('views')
The views folder contains subdirectories as follows-

views
|-homepage/
|    |-homepage.ejs
|    |-homepage.css
|    |-homepage.js
|
|-partials/
|     |-navbar.ejs
|     |-footer.ejs
|
|-payground/
|    |-playground.ejs
|    |-playground.css
|    |-playground.js

I rendered the homepage and realised that the CSS broke, because I didn’t specified the ./views/homepage as static.

Even though it’s not a problem right now, because I’ve onnly limited pages to render, but in future if I decide to create dynamic directories, I’ve no idea how would I make their particular folders static.

Is there any way, with which I can make a folder static, and all its subdirectories become static too.
I’ve seen people sayng that once the parent folder is declared static, all its subdirectories become static too which I agree,becasue my homepage.ejs was rendering fine(but without CSS), but, I’m pretty sure, my homepage’s css wasn’t rendering until I specifically added app.use(express,static('./views/homepage')) to my code.

Thanks in advance!

2

Answers


  1. To serve static files like CSS and JS, it is common to place them in a specific directory, such as public, look at this example.

    ejemplo_estroctura

    In your main configuration file (for example, app.js), you need to configure express to serve static files from the public directory:

    app.use(express.static(path.join(__dirname, 'public')));
    app.set('view engine', 'ejs');
    // example route
    app.get('/', (req, res) => {
        res.render('homepage/homepage');
    });
    

    In your .ejs files, you can include the corresponding CSS and JS files using the correct path to the static files. For example, in homepage.ejs:

    example-html

    I hope it works for you

    Login or Signup to reply.
  2. In order to get the files in sub-directories referenced, the URL path should be relative to the root in express.static.

    The below code will work since the url path in the link is relative to root.

    //server.js
    app.use(express.static('views'));
    
    //homepage.ejs
    <link rel="stylesheet" href="/homepage/homepage.css" />
    

    The below code will fail to load the css file since the url path is not relative.

    //homepage.ejs
    <link rel="stylesheet" href="/homepage.css" />
    

    However the below code will work since there are multiple directories to server static files and the root in the second express.static call will serve the file referenced.

    //server.js
    app.use(express.static('views'));
    app.use(express.static('views/homepage'));
    
    //homepage.ejs
    <link rel="stylesheet" href="/homepage.css" />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search