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

Rae*_*fai 5 node.js express angular-cli pug angular

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

那么对于这样的事情,最好的做法是什么?

Rae*_*fai 2

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

  • angular-cli.json中更改"index": "index.html""index": "index.pug"
  • 将index.html重命名为index.pug并将其内容更改为pug内容。
  • index.pug中,您应该有两个注释,用于放置样式和脚本,如下所示:

    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
    
    Run Code Online (Sandbox Code Playgroud)
  • 在根目录中创建 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);
    
    Run Code Online (Sandbox Code Playgroud)
  • 最后,在package.json 的postinstall添加以下内容:ng build --prod && node parse-index.js

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