当我使用 puppeteer 运行 gatsby build 时,我正在尝试为我的每个 Gatsby 帖子生成图像。我在我的 puppet.js
中包含了以下脚本:
const puppeteer = require('puppeteer')
const baseUrl = process.argv[2] || 'http://localhost:8000/'
const takeScreenshot = async (slug) => {
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
})
let url = `${baseUrl}/${slug}/thumbnail`
let destination = `/static/posts/${slug}-share.png`
let width = 440
let height = 220
const page = await browser.newPage()
await page.goto(url, {
waitUntil: 'networkidle2',
})
await page.screenshot({
path: destination,
clip: {
x: 0,
y: 0,
width,
height,
},
})
await browser.close()
res.status(200).send("ok");
}
const main = async (file) => {
const destinationFile = `/static/posts/${file}-share.png`
await takeScreenshot(file)
console.log(`Created ${file}`)
}
function generateImage(slug) {
const file = slug
main(file)
}
module.exports.generateImage = generateImage
我在 gatsby-node.js
中这样称呼它:
var image = require('./src/utils/puppet')
然后像这样执行:
const toolNodes = data.portfolio.nodes;
let slugs = [];
toolNodes.map(toolNode => slugs.push(toolNode.slug));
console.log(slugs)
slugs.forEach(node => {
image.generateImage(node)
})
在上面,我创建了一个 slug
值数组并为每个值运行函数 generateImage
。理论上,这个值应该传递给 puppet.js
文件,然后该文件应该使用它来导航到正确的 URL,截取屏幕截图并保存文件。
我得到了这个,而不是工作:
Navigation timeout of 30000 ms exceeded
TimeoutError: Navigation timeout of 30000 ms exceeded
我该如何解决这个问题?目前,我在目录中看不到任何图像输出。
此外,这种方式是否是个坏主意?这个脚本应该在我的 gatsby-node.js 中吗?如果没有,我从哪里运行它?
有关其他上下文,this is my gatsby-node.js file
答案 0 :(得分:1)
这有很多问题。
gatsby build
期间,Gatsby 开发服务器未运行,因此 localhost:8000
不太可能为您的网站提供服务以供 Puppeteer 抓取createPages
函数在 gatsby develop
的启动过程中比 Express 服务器绑定更早地被调用,因此在开发过程中运行此代码时,localhost:8000
同样不可用立>
takeScreenshot
是异步的,但是在对 resolve
返回的 Promise 调用 createPages
之前,您不会等待它完成,因此 Gatsby 不会等待它们完成如果您能够预先确定对它们的任何引用的路径,您可以考虑使用 onPostBuild
来生成这些图像。不过,您仍然需要运行服务器才能使 Puppeteer 可以使用这些页面(例如使用 Express),这可能会变得棘手,因为您还没有完成构建。