How to make jade loading the css file? (It doesn't work)

Viewed 105

Here is my directory

enter image description here

newTab.jade code

doctype html
html
    head
        title New Tab
        link(rel = 'stylesheet', type = 'text/css', href = '/public/index.css')
    body
        p hello world

index.css code

p{
    background-color: black;
    color: white;
}

app.js code

const express = require('express');
const app = express();
const port = 3000;
app.locals.pretty = true;
app.listen(port, function(){
    console.log("Server Connected port: "+port);
});

app.set('view engine', 'jade');
app.set('views', './views');

app.get('/', function(req, res){
    res.render('newTab');
});

jade file can't loading css file. I tried href = "/public/index.css" but it doesn't work too.

2 Answers

Append a middleware to Express to serve static files too.

In your app.js file:

// require path module to join your public folder with __dirname
const path = require('path');

//...

app.get('/', function(req, res){
    res.render('newTab');
});

app.use('/', express.static(path.join(__dirname, 'public')));

There are more things express.staticcan do. E.g. setting the maxAge for caching purpose:

// 31557600000ms = 1 year
app.use('/', express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

suggestion

try

doctype html
html
    head
        title New Tab
         include index.css
    body
        p hello world

on your newTab.jade file

and include index.css on views directory

Related