Skip to content

Commit

Permalink
fix(gatsby-plugin-image): Better StaticImage errors (#30271) (#30326)
Browse files Browse the repository at this point in the history
* fix(gatsby-plugin-image): Better StaticImage errors

* Apply suggestions from code review

Co-authored-by: LB <laurie@gatsbyjs.com>

Co-authored-by: LB <laurie@gatsbyjs.com>
(cherry picked from commit 8a0a4e8)

Co-authored-by: Matt Kane <matt@gatsbyjs.com>
  • Loading branch information
wardpeet and ascorbic authored Mar 18, 2021
1 parent 32d7adf commit 6f1beee
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 10 deletions.
3 changes: 2 additions & 1 deletion packages/gatsby-plugin-image/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,10 @@
"react-dom": "^16.9.0 || ^17.0.0"
},
"dependencies": {
"@babel/code-frame": "^7.12.13",
"@babel/parser": "^7.12.5",
"@babel/traverse": "^7.12.5",
"babel-jsx-utils": "^1.0.1",
"babel-jsx-utils": "^1.1.0",
"babel-plugin-remove-graphql-queries": "^3.1.0",
"camelcase": "^5.3.1",
"chokidar": "^3.5.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby-plugin-image/src/babel-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function normalizeProps(

export function evaluateImageAttributes(
nodePath: NodePath<JSXOpeningElement>,
onError?: (prop: string) => void
onError?: (prop: string, nodePath: NodePath<any>) => void
): Record<string, unknown> {
// Only get attributes that we need for generating the images
return normalizeProps(getAttributeValues(nodePath, onError, SHARP_ATTRIBUTES))
Expand Down
10 changes: 9 additions & 1 deletion packages/gatsby-plugin-image/src/node-apis/image-processing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export async function writeImages({
createNodeId,
createNode,
store,
filename,
}: {
images: Map<string, IStaticImageProps>
pathPrefix: string
Expand All @@ -80,11 +81,16 @@ export async function writeImages({
createNodeId: ParentSpanPluginArgs["createNodeId"]
createNode: Actions["createNode"]
store: Store
filename: string
}): Promise<void> {
const promises = [...images.entries()].map(
async ([hash, { src, ...args }]) => {
let file: FileSystemNode | undefined
let fullPath
if (!src) {
reporter.warn(`Missing StaticImage "src" in ${filename}.`)
return
}
if (isRemoteURL(src)) {
let createRemoteFileNode
try {
Expand Down Expand Up @@ -122,7 +128,9 @@ export async function writeImages({
fullPath = path.resolve(sourceDir, src)

if (!fs.existsSync(fullPath)) {
reporter.warn(`Could not find image "${src}". Looked for ${fullPath}`)
reporter.warn(
`Could not find image "${src}" in "${filename}". Looked for ${fullPath}.`
)
return
}

Expand Down
6 changes: 4 additions & 2 deletions packages/gatsby-plugin-image/src/node-apis/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ export function babelParseToAst(
* Extracts and returns the props from any that are found
*/
export const extractStaticImageProps = (
ast: babel.types.File
ast: babel.types.File,
onError?: (prop: string, nodePath: NodePath) => void
): Map<string, IStaticImageProps> => {
const images: Map<string, IStaticImageProps> = new Map()

Expand All @@ -89,7 +90,8 @@ export const extractStaticImageProps = (
}
const image = (evaluateImageAttributes(
// There's a conflict between the definition of NodePath in @babel/core and @babel/traverse
(nodePath as unknown) as NodePath<JSXOpeningElement>
(nodePath as unknown) as NodePath<JSXOpeningElement>,
onError
) as unknown) as IStaticImageProps
images.set(hashOptions(image), image)
},
Expand Down
36 changes: 35 additions & 1 deletion packages/gatsby-plugin-image/src/node-apis/preprocess-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import { PreprocessSourceArgs } from "gatsby"
import { babelParseToAst } from "./parser"
import path from "path"
import { extractStaticImageProps } from "./parser"
import { codeFrameColumns } from "@babel/code-frame"

import { writeImages } from "./image-processing"
import { getCacheDir } from "./node-utils"
import { stripIndents } from "common-tags"
const extensions: Array<string> = [`.js`, `.jsx`, `.tsx`]

export async function preprocessSource({
Expand All @@ -28,8 +31,38 @@ export async function preprocessSource({
const cacheDir = getCacheDir(root)

const ast = babelParseToAst(contents, filename)
reporter.setErrorMap({
"95314": {
text: (context): string =>
stripIndents`
Error extracting property "${context.prop}" from StaticImage component.
There are restrictions on how props can be passed to the StaticImage component. Learn more at https://gatsby.dev/static-image-props
${context.codeFrame}
`,
docsUrl: `https://gatsby.dev/static-image-props`,
level: `ERROR`,
category: `USER`,
},
})

const images = extractStaticImageProps(ast)
const images = extractStaticImageProps(ast, (prop, nodePath) => {
const { start, end } = nodePath.node.loc
const location = { start, end }
reporter.error({
id: `95314`,
filePath: filename,
location,
context: {
prop,
codeFrame: codeFrameColumns(contents, nodePath.node.loc, {
linesAbove: 6,
linesBelow: 6,
highlightCode: true,
}),
},
})
})

const sourceDir = path.dirname(filename)
await writeImages({
Expand All @@ -42,6 +75,7 @@ export async function preprocessSource({
createNodeId,
createNode,
store,
filename,
})

return
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6132,10 +6132,10 @@ babel-jest@^24.9.0:
chalk "^2.4.2"
slash "^2.0.0"

babel-jsx-utils@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/babel-jsx-utils/-/babel-jsx-utils-1.0.1.tgz#f2d171cba526594e7d69e9893d634502cf950f07"
integrity sha512-Qph/atlQiSvfmkoIZ9VA+t8dA0ex2TwL37rkhLT9YLJdhaTMZ2HSM2QGzbqjLWanKA+I3wRQJjjhtuIEgesuLw==
babel-jsx-utils@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/babel-jsx-utils/-/babel-jsx-utils-1.1.0.tgz#304ce4fce0c86cbeee849551a45eb4ed1036381a"
integrity sha512-Mh1j/rw4xM9T3YICkw22aBQ78FhsHdsmlb9NEk4uVAFBOg+Ez9ZgXXHugoBPCZui3XLomk/7/JBBH4daJqTkQQ==

babel-loader@^8.2.2:
version "8.2.2"
Expand Down

0 comments on commit 6f1beee

Please sign in to comment.