PUG中的绝对路径

卡坦德拉克斯

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

如果路径是绝对路径(例如,包含 /root.pug),则通过添加 options.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 文件的正确方法是什么

卡坦德拉克斯

Express.js应用程序中,只需使用设置 Web 根目录,app.use(express.static('public'))以便应用程序知道从何处获取静态文件。app.locals.basedir = __dirname不需要。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章