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
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.In your main configuration file (for example, app.js), you need to configure express to serve static files from the
public
directory: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
:I hope it works for you
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.
The below code will fail to load the css file since the url path is not relative.
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.