Absolute path in PUG

六眼飞鱼酱① 提交于 2020-05-28 04:44:28

问题


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?


回答1:


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')


来源:https://stackoverflow.com/questions/45676302/absolute-path-in-pug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!