将 pug 模板编译为单个客户端 js 文件 [英] compiling pug templates to single client side js file

查看:37
本文介绍了将 pug 模板编译为单个客户端 js 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 pug 并将其用于一个小型单页应用程序.我正在使用编译为 javascript 函数的模板,我将在我的 SPA 中使用这些函数来呈现 HTML.使用 pug-cli,我能够生成多个 .js 文件,每个文件都包含所需的模板函数.但是,我不想编译多个 javascript 文件,而是想将所有函数合并到一个简单的template.js"文件中,然后我可以从我的客户端应用程序调用该文件.这是我目前使用的命令

I just started working with pug and am using it for a small single page app. I'm using templates that are compiled to javascript functions that I will use in my SPA to render HTML. Using the pug-cli, I am able to generate multiple .js files that each contain the desired template function. However, instead of compiling multiple javascript files, I'd like to merge all the functions in a simple 'template.js' file that I can then call from my client app. Here's the command I'm currently using

pug -c --name-after-file -w .\views\ -o .\public\

我用谷歌搜索,在 Stackoverflow 上搜索,还发现 pug API 本身具有 pug.compileFileClient 可能是为 Express 应用程序执行此操作.但是,我找不到这个功能是否在 pug-cli 中实现.

I've googled it, searched on Stackoverflow, and also found out that the pug API itself has the pug.compileFileClient that is meant to do this perhaps for an Express app. However, I couldn't find if this functionality is implemented in the pug-cli.

推荐答案

有一个 npm 包叫做 puglatizer 获取 pug 模板目录并将其编译为单个 .js 文件,该文件可以包含在您的 html 文件中,并且可以调用单独的渲染函数来生成 html.

There is an npm package called puglatizer that takes a directory of pug templates and compiles it into single .js file that can be included in your html file and individual render functions can be called to produce the html.

它既可以使用 CLI 在命令行中使用,也可以通过 require 导入,可以在构建过程中以编程方式调用.

It can be used both at the command line using a CLI or imported via require can called programmatically in your build process.

我最终使用了 CLI 版本.只需使用以下命令全局安装软件包:

I ended up using the CLI version. Simply install the package globally using:

npm install puglatizer -g

然后运行 ​​puglatizer -d path/to/templates -o/path/to/output/templates.js

这会将 path/to/templates 文件夹中的所有模板编译为 /path/to/output 中的 templates.js 文件>.

This will compile all the templates in the path/to/templates folder to a templates.js file in /path/to/output.

通过脚本标记将生成的文件包含在您的 html 页面中.

Include the generated file in your html page via the script tag.

然后您可以通过调用 puglatizer.TemplateFileName({data:"myData"}) 在 Javascript 中调用模板,其中 TemplateFileName 是 pug 模板上的文件名在 path/to/templates 目录中.

Then you can call the template in Javascript by invoking puglatizer.TemplateFileName({data:"myData"}) where TemplateFileName is the file name of on your pug templates in the path/to/templates directory.

这篇关于将 pug 模板编译为单个客户端 js 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆