如何在AWS Lambda中使用Node.js函数与HTML模板引擎?

huangapple go评论91阅读模式
英文:

How to use an HTML templating engine with a Node.js function in an AWS lambda?

问题

我有一个lambda函数,应该返回一个HTML页面。

这个页面需要一些动态变量以及自定义样式表才能正常工作。

我已经尝试了以字符串形式返回HTML,设置正确的内容类型,并在字符串中替换我需要的动态变量。这有效。

然而,我想使用一个模板引擎,而不是将HTML字符串写成JavaScript。

我尝试使用nunjucks,但它无法找到我的HTML文件,因为构建文件夹中只有一个app.js文件。

英文:

I have a lambda function that is supposed to return an HTML page.

This page needs a number of dynamic variables as well as custom stylesheets to function properly.

I have tried the regular way of returning HTML as a string, setting the correct content-type and substituting the dynamic variables I need within that string. This works.

However, I want to use a templating engine rather than writing out strings of HTML as Javascript.

I've tried using nunjucks but it's unable to find my HTML file since the build folder only has an app.js in it.

答案1

得分: 1

假设您的所有文件都是要上传到AWS的捆绑包的一部分,这是我修复HTML文件未找到问题的方法:

我的esbuild的输出只是一个单独的app.js文件,最初这就是被推送到AWS的内容。我不得不在构建阶段添加一个cp命令,将所有的.html文件从我的工作目录复制到构建目录。

完成这个操作后,您可以简单地使用path__dirname的组合来引用您的.html文件,然后Nunjucks(或任何其他模板引擎)应该能够无问题地找到您的文件。

英文:

Assuming all your files are part of the bundle being uploaded to AWS, here's how I fixed the issue of the HTML file not being found:

The output of my esbuild is just a single app.js file and this is what was originally being pushed to AWS. I had to add a cp command to my build phase which copies all my .html files from my working directory to the build directory.

Once this is done, you can simply refer to your .html files using a combination of path and __dirname and Nunjucks (or any other templating engine) should be able to find your files without any issues.

huangapple
  • 本文由 发表于 2023年1月10日 06:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75063399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定