问题
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\
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.
回答1:
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.
It can be used both at the command line using a CLI or imported via require can called programmatically in your build process.
I ended up using the CLI version. Simply install the package globally using:
npm install puglatizer -g
Then run puglatizer -d path/to/templates -o /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.
Include the generated file in your html page via the script tag.
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.
来源:https://stackoverflow.com/questions/52067308/compiling-pug-templates-to-single-client-side-js-file