Kathandrax
Kathandrax

Reputation: 1054

Absolute path in PUG

According to the PUG documentation (https://pugjs.org/language/includes.html):

If the path is absolute (e.g., include /root.pug), it is resolved by prepending options.basedir. Otherwise, paths are resolved relative to the current file being compiled.

Which I understand consists of passing the path preposition as an option to res.render(). However, I want to avoid the trouble of repeating myself as much as I can and would prefer a top-level solution.

I tried using app.locals.basedir but my code fails to preprend the basedir path. The file therefore cannot be found.

Here is the backbone of my Express.js app index:

// index.js

const express = require('express');
const app = express();

const path = require('path');

app.locals.basedir = __dirname;

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

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

app.listen(3000, function(){
  console.log('Server started on port 3000');
});

My PUG file is as follows:

// views/index.pug

doctype html
html
  head
    script(type='text/javascript' src='/public/lib/map.js' defer='defer')

    title ExpressApp
  body
    h1 Hello, World!

And my project structure:

project/
  index.js
  views/
    index.pug
  public/
    lib/
      map.js

What is the correct way of inserting a javascript file using an absolute path in a PUG file?

Upvotes: 4

Views: 7873

Answers (1)

Kathandrax
Kathandrax

Reputation: 1054

In the Express.js app, the web root simply needs to be set using app.use(express.static('public')) so that the application knows where to fetch the static files. app.locals.basedir = __dirname is not needed.

In the PUG file, the script should therefore be inserted as follows:

script(type='text/javascript' src='/lib/map.js' defer='defer')

Upvotes: 4

Related Questions