首页 > 解决方案 > 如何在没有 Node 的情况下在 .pug 文件和链接的 .js 文件之间交换数据?

问题描述

是否可以在不使用 Node的情况下将数据从.js文件传递到文件?.pug我正在使用一个非常基本的设置来运行我的项目并将其与 Parcel.js 捆绑在一起。我没有使用带有 Express 的 Node.js 后端,我也不渴望这样做。我只是希望能够在我的app.js-file 中获取数据并使用 Pug 显示它。但即使这个设置也没有name在页面上显示 - 变量:

指数.pug

doctype html
html(lang="en")
    head
        title Homepage
    body
        p My name is #{name}
        script(type="module", src="./app.js")

应用程序.js

const name = "Holy Kiwi";

包.json

{
  "name": "frontend-javascript-edhub-pug",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "start": "parcel index.pug",
    "build": "parcel build index.pug"
  },
  "devDependencies": {
    "@parcel/transformer-pug": "^2.0.0",
    "parcel": "^2.0.0",
  },
  "dependencies": {
    "pug": "^3.0.2"
  }
}

我尝试过的其他没有用的东西

我真的希望你能帮助我!

标签: javascriptnode.jspugparceljsscript-tag

解决方案


当您安装了pug软件包后,您可以使用以下renderFile 方法

const pug = require("pug");
const html = pug.renderFile("./path_to/index.pug", { name: "Holy Kiwi"});

上面在 object 中产生了以下字符串html,你可以根据自己的需要“显示”它:

<!DOCTYPE html><html lang="en"><head><title>Homepage</title></head><body><p>My name is Holy Kiwi</p><script type="module" src="./app.js"></script></body></html>

推荐阅读