javascript - 如何在电子上渲染 pugjs?

标签 javascript node.js pugjs

我正在尝试在 electron 上使用 pug。

我有一个问题,我的第二个 .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 只会输出哈巴狗代码本身。

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

最佳答案

Pug 是一种可以用来更有效地编写 HTML 的语言。然而,它不受任何浏览器的支持——包括 Electron 使用的 Chromium—— native ,因此您要么必须使用 pug package 将其转换为 HTML。在运行时或将您的 .pug 文件编译为 .html 文件(使用任务运行器插件,如 gulp-pug for Gulp),然后加载生成的 .html 代码中的文件。

应用于代码的最快解决方案是像这样使用 pug.render:

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;
});

关于javascript - 如何在电子上渲染 pugjs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863249/

相关文章:

javascript - 正则表达式从 Windows 的文件名中删除特殊字符

javascript - 如何使用 ES6 导入重新导入模块

intellij-idea - Intellij IDEA 中对 Pug 模板引擎的支持

javascript - 单击按钮时避免浏览器自动完成表单功能

javascript - Angular 如何污染全局空间?

NODE.JS - 如何正确处理操作系统和 URL 样式 "paths"的混合?

node.js - package.json 启动脚本,babel-node : not found on heroku deploy

node.js - 错误 : Cannot find module 'pug'

javascript - Jade/PUG JSON 插值

javascript - JavaScript 访问对象属性的运行时复杂度 O(?) 是多少?