2

我正在尝试在电子上使用哈巴狗。

我有一个问题,我的第二个.pug文件没有正确呈现,它只是输出哈巴狗代码本身。

首先,我有这个由 main.js 加载的主 pug 文件

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

那么 index.js 只会调用 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;
});

.innerHTML只会输出哈巴狗代码本身。

请帮助我如何解决。我将不胜感激任何建议或提示,谢谢。

4

1 回答 1

3

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;
});
于 2017-09-03T16:51:33.800 回答