Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render pug file dynamically instead of using the static angular-cli index.html?

I have an angular 2 application and I need to render index.pug instead of using the static index.html of angular-cli.

So what's the best practice for such thing?

like image 386
Raeef Refai Avatar asked Oct 30 '22 12:10

Raeef Refai


1 Answers

Well, after googling a lot without any luck, I came up with the following workaround:

  • In angular-cli.json change "index": "index.html" to "index": "index.pug"
  • Rename index.html to index.pug and change its content to be pug content.
  • In index.pug you should have two comments where you want to put your styles and script as the following:

    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
    
  • Create parse-index.js in your root and put the following code:

    '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);
    
  • Finally, in postinstall in package.json put this: ng build --prod && node parse-index.js

I wish if someone introduce a better way!

like image 80
Raeef Refai Avatar answered Nov 15 '22 07:11

Raeef Refai