问题
I have a React Component in a Gatsby app that is using the useStaticQuery hook to pull in data from the GraphQL layer. This component gets used in my application, but it also gets used as part of a JavaScript embed/widget that is created in a separate Webpack configuration.
I don't want the widget to depend on Gatsby, so I've shimmed the relevant bits of Gatsby, but I still need to pass in data to the shim I've created for useStaticQuery
. I found that my Gatsby app is generating a file at public/static/d/2250905522.json
that contains a perfect representation of the query data, and I'd like to use it like so:
// This file gets substituted when importing from `gatsby`
import queryResult from "../public/static/d/2250905522.json"
export const useStaticQuery = () => queryResult.data
export const graphql = () => {}
This works, but I haven't figured out where this is coming from or how to determine the file name in a way that is deterministic/stable. How is Gatsby determining this file name, and what internals might I use to do the same?
Edit: I found this routine in the Gatsby codebase that appears to be using staticQueryComponent.hash
to determine the number. staticQueryComponent
is being destructured from store.getState()
where store
is associated with Redux, but I'm still not sure where the hash is being determined yet.
Edit 2: Found another mention of this in the documentation here. It sounds like hash
is a hash of the query itself, so this will change over time if the query changes (which is likely), so I'm still looking for the routine used to compute the hash.
回答1:
Gatsby is using murmurhash with a seed of "abc"
to calculate the hash of the full text of the query (including whitespace). This occurs in babel-plugin-remove-graphql-queries.
Since the reused components are isolated from Gatsby, the graphql
tagged template literal can be shimmed in order to get the original query for hashing:
// webpack.config.js
module.exports = {
resolve: {
alias: {
gatsby: path.resolve(__dirname, "gatsby-shim.js"),
},
},
}
// gatsby-shim.js
import murmurhash from "babel-plugin-remove-graphql-queries/murmur"
const GATSBY_HASH_SEED = "abc"
function hashQuery(query) {
return murmurhash(query, GATSBY_HASH_SEED).toString()
}
export const graphql = query => hashQuery(query.raw[0])
This results in the query hash being passed into useStaticQuery
, which can be shimmed similarly to retrieve the cached query from disk.
来源:https://stackoverflow.com/questions/58942573/access-json-chunk-exported-from-gatsby-static-query