-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
preprocess-source.ts
81 lines (73 loc) · 2 KB
/
preprocess-source.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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({
filename,
contents,
pathPrefix,
cache,
reporter,
store,
createNodeId,
actions: { createNode },
}: PreprocessSourceArgs): Promise<void> {
if (
!contents.includes(`StaticImage`) ||
!contents.includes(`gatsby-plugin-image`) ||
!extensions.includes(path.extname(filename))
) {
return
}
const root = store.getState().program.directory
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, (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({
images,
pathPrefix,
cache,
reporter,
cacheDir,
sourceDir,
createNodeId,
createNode,
filename,
})
return
}