У меня есть приложения React, которые я упаковываю и помещаю в каталог моего сервера nodejs для Puppeteer, чтобы рендерить и захватывать некоторые HTML. Вот мне рабочее решение:
Создайте следующие файлы с соответствующим содержимым:
/assets
- index.html
- bundle.js
/render.js
<!-- /assets/index.html -->
<html>
<body>
This is a test index.html file
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
// /assets/bundle.js
(() => {
document.getElementById('root').innerHTML = "The JS bundle loaded!! " + new Date().toISOString()
})()
// /render.js
const puppeteer = require('puppeteer')
const fs = require('fs')
const path = require('path')
const browser = await puppeteer.launch();
const page = await browser.newPage();
const assetFilePath = path.join(__dirname, "./assets/index.html");
await page.setRequestInterception(true);
page.on("request", interceptedRequest => {
const url = interceptedRequest.url();
if (url.startsWith("file://") && !url.match(assetFilePath)) {
interceptedRequest.respond({
body: fs.readFileSync(
path.join(__dirname, "./assets/", url.replace("file://", ""))
)
});
} else {
interceptedRequest.continue();
}
});
await page.goto(`file://${assetFilePath}`, {
waitUntil: "networkidle0"
});
const html = await page.evaluate(() => {
return document.documentElement.innerHTML;
});
console.log(html);
Пробег npm install puppeteer
Выполнить node render.js