本文介绍了Pug和Parcel无法使用动态本地人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Express应用程序,该应用程序使用Pug模板和用于打包程序的Parcel.根据包裹 docs 的说法,我可以使用一个配置文件来存储我的本地人pug.config.js,我需要在运行时将本地人动态添加到模板中.可以这样做吗?

I have an Express app using Pug templates and Parcel for my bundler. According to the Parcel docs, I can have a config file that stores my locals pug.config.js, however, I need to dynamically add locals to my templates at runtime. Is it possible to do this?

这是我的文件:

index.pug

...
h1 #{isAuthenticated}
h1 #{env}
...

pug.config.js

module.exports = {
  locals: {
    env: process.env.NODE_ENV
  }
}

app.js

const Bundler = require('parcel-bundler')
const bundler = new Bundler(path.resolve(__dirname, 'views/index.pug'))

app
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'pug')
.use(function(req, res, next) {
     res.locals.isAuthenticated = 'true'
     next()
})
.use(bundler.middleware())

这里我试图将本地变量var isAuthenticated设置为'true',但是当渲染index.pug变量为空时,同时存在我的pug.config.js文件中的env var.

Here I am attempting to set a locals var isAuthenticated to 'true', however when rendering index.pug the variable is empty, meanwhile, the env var from my pug.config.js file is present.

现在,如果我尝试使用res.render('index', {isAuthenticated: 'true'})在控制器函数中呈现页面,则变量isAuthenticated现在存在,但是env为空.

Now, if I try to render a page in my controller functions with res.render('index', {isAuthenticated: 'true'}) the variable isAuthenticated is now present, however env is empty.

我想知道我是否在这里遗漏了某些东西,或者它是否按预期工作?

I'm wondering if I am missing something here or if this works as expected?

推荐答案

我已经简要试用了包裹.开箱即用的体验很棒,但是当涉及到高级配置时,这是很糟糕的.这是设计使然,包裹只是反对config的想法.一切都基于惯例.

I have briefly tried out parcel. The out of box experience is awesome, but when it comes to advanced configuration, it's terrible. That's kinda by design, parcel just oppose the idea of config. Everything bases on convention.

所以我检查了源代码.事实证明,包裹仅从'.pugrc', '.pugrc.js', 'pug.config.js'中获取哈巴狗配置.

So i check the source code. Turns out parcel only takes pug config from '.pugrc', '.pugrc.js', 'pug.config.js'.

如果选择保留包裹方式,则可以尝试将locals值写回到磁盘上的这些文件之一.需要进行测试,可能会有一些异步问题需要调试.

If you choose to stick with parcel way, you can try write your locals value back to one of these files on disk. Need to test it out, might have some async problems to debug.

我个人更喜欢以下方法.您将pug用作真正的模板引擎,直接使用pug.compile/render API生成html.然后,您将这些html进一步传送到宗地,它仍将完成工作的捆绑"部分.

I personally prefer following method. You use pug as a real template engine, directly use the pug.compile/render API to produce html. You then pipe these html further to parcel, it'll still do the "bundling" part of the job.

这篇关于Pug和Parcel无法使用动态本地人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 22:29