I have an API that returns to me raw html. I want to extract some specific information. I was using Jquery in the past to do so :
fetch(url)
.then((html) => {
const parsed = $(html)
return parsed.find(id).attr('src')
})
something like that.
Now that I moved to NextJs, I want to do this operation at compile time to do server rendering. In this function:
export async function getStaticProps({ params }) {
const data = await getData(params.slug)
return { props: { data } }
}
I encountered a first problem where jquery
needs a window
.
I solved it by using this code:
const jsdom = require('jsdom')
const $ = require('jquery')(new jsdom.JSDOM().window)
For someone that is encountering this problem too, I first had to resolve a module missing: canvas
. I solved this by adding:
webpack: (config, { webpack }) => {
config.plugins.push(new webpack.IgnorePlugin(/canvas/, /jsdom$/))
return config
},
to my next.config.js
.
But now I have a problem when I do: $(html)
, it says that $ is not a function
.
I tried this:
const jsdom = require('jsdom')
const window = new jsdom.JSDOM().window
window.document.body.innerHTML = html
const parsed = require('jquery')(window)
parsed.find(id).attr('src')
but now I get parsed.find(id).attr is not a function
.
Anyone could help ?
Thank you very much.