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

标签 node.js angular express pug angular-cli

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

那么这种事情的最佳实践是什么?

最佳答案

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

  • 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
    
  • 在您的根目录中创建 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 && node parse-index.js

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

关于node.js - 如何动态呈现 pug 文件而不是使用静态 angular-cli index.html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182244/

相关文章:

angular - Jest 遇到意外 token - 导入 (Angular CLI 6)

mysql - 使用 MySQL 作为 session 存储时的重定向问题

javascript - 使用nodejs替换文件中的行

javascript - Angular 2 : Binding Data using Elasticsearch Client

c# - ASP.NET C#,将对象返回给 Angular

node.js - 保存首次登录历史记录后 ExpressJS 应用程序登录失败

javascript - app.configure(function){} typeerror undefined is not a function

node.js - TypeScript - 使用 Grunt 在后台编译 TypeScript

javascript - WebStorm 找不到导出函数的用法

node.js - ZeroMQ PUSH/PULL 通信不能通过 IPC 工作,但可以通过 TCP 工作