问题
I am developing an app in GatsbyJS, and export
ing one of my GraphQL fragments as such:
import { graphql } from 'gatsby';
export const w300Image = graphql`
fragment w300Image on File {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
presentationWidth
}
}
}
`;
export const squareImage = graphql`
fragment squareImage on File {
childImageSharp {
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
presentationWidth
}
}
}
`;
I import
and use squareImage
as such:
import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
import { squareImage } from '../graphql/imageFragments';
import NonStretchedImage from './nonStretchedImage';
const Image = () => {
const data = useStaticQuery(graphql`
query {
astronaut: file(relativePath: { eq: "gatsby-astronaut.png" }) {
...squareImage
}
}
`);
return <NonStretchedImage fluid={data.astronaut.childImageSharp.fluid} alt="nFront mobile development" />;
};
Note: My IDE warns me that the squareImage
import
is never read. However, since that is not true, I am assuming it is just incapable of picking up its presence inside the GraphQL query.
Question
If I change the export
to the below (i.e. move the export
to the end of the file), it crashes when compiling with the following error message:
Error: Invariant Violation: GraphQLCompilerContext: Unknown document
squareImage
.
New export code (only difference is the export
s having moved to the end):
import { graphql } from 'gatsby';
const w300Image = graphql`
fragment w300Image on File {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
presentationWidth
}
}
}
`;
const squareImage = graphql`
fragment squareImage on File {
childImageSharp {
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
presentationWidth
}
}
}
`;
export { squareImage, w300Image };
Any idea what's going on here? I thought the two export
s were identical? Perhaps tree shaking happens in only one scenario?
EDIT
Added a console.log(squareImage)
after the import
, and the error still appears. In other words, tree shaking is not the culprit.
回答1:
TL:DR: You don't need to import fragment to use it in query with Gatsby
Gatsby pulls graphql fragments & queries out of your file and execute them independently. Because of this, exporting / importing graphql fragment works a little differently.
Since all query lives in the same namespace, once you export a named fragment in any of your files, it's available 'globally', i.e you can use it in other queries & fragment without importing them explitcitly.
This is why you can use the fragment GatsbyImageSharpFluid without importing it anywhere in your code.
Update: Gatsby only looks for query inside tagged template in named export i.e export const queryName = graphql``
, this explains why it breaks when you switch export style.
来源:https://stackoverflow.com/questions/55464780/export-module-in-front-of-function-vs-at-end