PUG中的绝对路径

时间:2017-08-14 14:00:44

标签: javascript node.js express pug

根据 PUG 文档(https://pugjs.org/language/includes.html):

  

如果路径是绝对路径(例如,包括/root.pug),则解析为   预先选择.basedir。否则,路径将相对于   正在编译的当前文件。

我理解的是将路径介词作为res.render()的选项传递。 但是,我希望避免尽可能多地重复自己的麻烦,并希望采用顶级解决方案。

我尝试使用app.locals.basedir,但我的代码无法预先建立basedir路径。因此无法找到该文件。

以下是我的 Express.js 应用程序索引的主干:

// 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');
});

我的 PUG 文件如下:

// views/index.pug

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

    title ExpressApp
  body
    h1 Hello, World!

我的项目结构:

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

PUG 文件中使用绝对路径插入javascript文件的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

Express.js 应用程序中,只需使用app.use(express.static('public'))设置Web根目录,以便应用程序知道在哪里获取静态文件。

PUG 文件中,应按如下方式插入脚本:

app.locals.basedir = __dirname
相关问题