3

I am trying to use pug on electron.

I have a question my second .pug file is not rendered correctly, it just output the pug code itself.

First I have this main pug file that was loaded by the main.js

doctype
html(lang='en')
  head
    meta(charset='utf-8')
    title HIMS
  body
    div(id="app")
    script.
      require('./index.js')

then the index.js will just call the login.js

const fs = require('fs');
const path = require('path');

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', path.join(__dirname, 'style.css'));
document.head.appendChild(link);

const login = path.join(__dirname, 'login.pug');
fs.readFile(login, 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    document.getElementById('app')
        .innerHTML = data;
});

but the .innerHTML will just output the pug code itself.

Please help how I can fix. I will appreciate any advice or hint will come, thanks.

zer09
  • 1,507
  • 2
  • 28
  • 48

1 Answers1

4

Pug is a language that can be used to write HTML more effectively. It is however not supported by any browser – including Chromium which is used by Electron – natively, so you either have to convert it to HTML using the pug package at runtime or compile your .pug files to .html files (using task runner plugins like gulp-pug for Gulp) and then load the generated .html files in your code.

The quickest solution to apply to your code is to use pug.render like this:

const fs = require('fs');
const path = require('path');
const pug = require('pug');

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', path.join(__dirname, 'style.css'));
document.head.appendChild(link);

const login = path.join(__dirname, 'login.pug');
fs.readFile(login, 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    const htmlData = pug.render(data)
    document.getElementById('app')
        .innerHTML = htmlData;
});
Niklas Higi
  • 2,188
  • 1
  • 14
  • 30