问题
I'm starting a greenfield Gatsby project and my question is regarding creating pages programmatically.
In general is it better to:
- query for just IDs (via the
graphql(/* ... */)
createPages API) and then use the ID to re-query related data per page - query for the whole object and send it to the page via
pageContext
?
This is for an e-commerce + blog site with 500+ posts and products that need to be created programmatically.
What method is better considering things like DX (e.g. startup times, reload times), maintainability, and build times? Why?
回答1:
I posted this question on the Gatsby Discord and LekoArts
opted for method 1 which is the clear correct choice.
This was their response from the Discord:
because otherwhise you'll bloat the data that each page loads as every page then will load everything you'll query in gatsby-node. Gatsby also has to query every node then which can go into the millions, like in this issue https://github.com/gatsbyjs/gatsby/issues/20671
On the other hand, if you pass the id you can get great speed improvements https://github.com/gatsbyjs/gatsby/pull/20609
Here is another paste from the first GitHub issue LekoArts
linked by the Gatsby contributor, vladar
:
@MartinMikusat thanks for bringing this up!
It looks like you put too much data into the page context. You put your whole data set into it: https://github.com/MartinMikusat/gatsby-reproduce/blob/master/gatsby-node.esm.js#L83
Page context is not meant for passing data to pages. It is meant to pass simple parameters that could be later passed to the GraphQL query of the page as variables.
There is an overhead associated with context - Gatsby has to visit every field of every object in context to infer SitePageContext type.
You have pages for 850 nodes (SanityLens in your example) and each page context has all the nodes in it. Also, each node has about 30 fields. It means that Gatsby has to visit 850 * 850 * 30 fields (which is approx. 21,7 million).
We could do better by showing a warning in cases like this (when the context is not used appropriately) and we have an issue exactly for this problem: #14213
Sorry if it is a bit confusing and thanks for using Gatsby 💜
来源:https://stackoverflow.com/questions/59865997/what-is-the-best-practice-for-creating-pages-programmatically-in-gatsby