如何动态呈现 pug 文件而不是使用静态 angular-cli index.html?

Posted

技术标签:

【中文标题】如何动态呈现 pug 文件而不是使用静态 angular-cli index.html?【英文标题】:How to render pug file dynamically instead of using the static angular-cli index.html? 【发布时间】:2017-06-30 03:37:32 【问题描述】:

我有一个 Angular 2 应用程序,我需要渲染 index.pug 而不是使用 angular-cli 的静态 index.html

那么这种事情的最佳做法是什么?

【问题讨论】:

【参考方案1】:

好吧,在没有任何运气的情况下进行了很多谷歌搜索后,我想出了以下解决方法:

angular-cli.json 中将 "index": "index.html" 更改为 "index": "index.pug"index.html 重命名为 index.pug 并将其内容更改为 pug 内容。

index.pug 中,您应该有两个 cmets 来放置您的样式和脚本,如下所示:

head
  // the next comment is important to replace with styles.
  //- styles
body
  app-root Loading...
  // the next comment is important to replace with scripts.
  //- scripts

在你的根目录下创建 parse-index.js 并输入以下代码:

'use strict';

const fs = require('fs');

const INDENT = '    ';

const INDEX = './dist/index.pug';

let index = fs.readFileSync(INDEX);
index = index.toString()
  .replace(/<(\s+)?head(\s+)?>|<(\s+)?\/(\s+)?head(\s+)?>/g, '');

let linkPattern = /<(\s+)?link[^<>]+\/?(\s+)?>/g;

let links = index.match(linkPattern);

let scriptPattern = /<(\s+)?script[^<]+<(\s+)?\/(\s+)?script(\s+)?>/g;

let scripts = index.match(scriptPattern);

index = index.replace(linkPattern, '');
index = index.replace(scriptPattern, '');

scripts.forEach((script, index) => 
  scripts[index] = script.replace(/<|>.+/g, '').replace(/\s/, '(') + ')';
);

links.forEach((link, index) => 
  links[index] = link.replace(/<|\/(\s+)?>(.+)?/g, '')
    .replace(/\s/, '(') + ')';
);

index = index.replace(
  /\/\/(\s+)?-?(\s+)?scripts/g, scripts.join('\n' + INDENT)
);

index = index.replace(/\/\/(\s+)?-?(\s+)?styles/g, links.join('\n' + INDENT));

fs.writeFileSync(INDEX, index);
最后,在 package.jsonpostinstall 中输入:ng build --prod &amp;&amp; node parse-index.js

希望有人介绍更好的方法!

【讨论】:

【参考方案2】:

看this manual,可以覆盖angular-cli webpack config。

【讨论】:

以上是关于如何动态呈现 pug 文件而不是使用静态 angular-cli index.html?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Swashbuckle 的 SwaggerUI 显示静态 swagger.json 文件而不是 SwaggerGen 的动态创建的定义?

如何在 webpack 中加载 Pug 模板而不编译为 HTML?

Pug和Parcel无法使用动态本地人

如何使用 Webpack 捆绑 Express Js (NodeJs) 和 Pug 引擎?

如何将数组变量从javascript传递到pug文件?

如何在动态呈现中为搜索引擎用户代理提供静态 HTML?