/
gatsby-layout-loader.ts
262 lines (239 loc) · 7.02 KB
/
gatsby-layout-loader.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* eslint-disable @babel/no-invalid-this */
import path from "path"
import type { NodePluginArgs } from "gatsby"
import { slash } from "gatsby-core-utils/path"
import { getPathToContentComponent } from "gatsby-core-utils/parse-component-path"
import type {
Program,
Declaration,
Expression,
ExportDefaultDeclaration,
Identifier,
FunctionDeclaration,
} from "estree"
import type { LoaderDefinition } from "webpack"
import type { IMdxPluginOptions } from "./plugin-options"
import { ERROR_CODES } from "./error-utils"
import { cachedImport } from "./cache-helpers"
export interface IGatsbyLayoutLoaderOptions {
options: IMdxPluginOptions
nodeExists: (path: string) => Promise<boolean>
reporter: NodePluginArgs["reporter"]
}
// Wrap MDX content with Gatsby Layout component
const gatsbyLayoutLoader: LoaderDefinition = async function (
source
): Promise<string | Buffer> {
const { nodeExists, reporter } =
this.getOptions() as IGatsbyLayoutLoaderOptions
// Figure out if the path to the MDX file is passed as a
// resource query param or if the MDX file is directly loaded as path.
const mdxPath = getPathToContentComponent(
`${this.resourcePath}${this.resourceQuery}`
)
if (!(await nodeExists(mdxPath))) {
reporter.panicOnBuild({
id: ERROR_CODES.NonExistentFileNode,
context: {
resourcePath: this.resourcePath,
mdxPath,
},
})
}
// add mdx dependency to webpack
this.addDependency(path.resolve(mdxPath))
const acorn = await cachedImport<typeof import("acorn")>(`acorn`)
// @ts-ignore - We typecast below
const { default: jsx } = await cachedImport(`acorn-jsx`)
const { generate } = await cachedImport<typeof import("astring")>(`astring`)
const { buildJsx } = await cachedImport<
typeof import("estree-util-build-jsx")
>(`estree-util-build-jsx`)
const JSX = jsx as typeof import("acorn-jsx")
try {
const tree = acorn.Parser.extend(JSX()).parse(source, {
ecmaVersion: 2020,
sourceType: `module`,
locations: true,
})
const AST = tree as unknown as Program
// Throw when tree is not a Program
if (!AST.body && !AST.sourceType) {
reporter.panicOnBuild({
id: ERROR_CODES.InvalidAcornAST,
context: {
resourcePath: this.resourcePath,
mdxPath,
},
})
}
/**
* Inject import to actual MDX file at the top of the file
* Input:
* [none]
* Output:
* import GATSBY_COMPILED_MDX from "/absolute/path/to/content.mdx"
*/
AST.body.unshift({
type: `ImportDeclaration`,
specifiers: [
{
type: `ImportDefaultSpecifier`,
local: {
type: `Identifier`,
name: `GATSBY_COMPILED_MDX`,
},
},
],
source: {
type: `Literal`,
value: slash(mdxPath),
},
})
let hasClassicReactImport = false
/**
* Replace default export with wrapper function that injects compiled MDX as children
* Input:
* export default PageTemplate
* Output:
* export default (props) => <PageTemplate {...props}>{GATSBY_COMPILED_MDX}</PageTemplate>
**/
const newBody: Array<any> = []
AST.body.forEach(child => {
if (
child.type === `ImportDeclaration` &&
child.source.value === `react`
) {
hasClassicReactImport = true
}
if (child.type !== `ExportDefaultDeclaration`) {
newBody.push(child)
return
}
const declaration = child.declaration as Declaration | Expression
const pageComponentName =
(declaration as FunctionDeclaration).id?.name ||
(declaration as Identifier).name ||
null
if (!pageComponentName) {
reporter.panicOnBuild({
id: ERROR_CODES.NonDeterminableExportName,
context: {
resourcePath: this.resourcePath,
},
})
}
newBody.push(declaration)
newBody.push({
type: `ExportDefaultDeclaration`,
declaration: {
type: `FunctionDeclaration`,
id: {
type: `Identifier`,
name: `GatsbyMDXWrapper`,
},
expression: false,
generator: false,
async: false,
params: [
{
type: `Identifier`,
name: `props`,
},
],
body: {
type: `BlockStatement`,
body: [
{
type: `ReturnStatement`,
argument: {
type: `JSXElement`,
openingElement: {
type: `JSXOpeningElement`,
attributes: [
{
type: `JSXSpreadAttribute`,
argument: {
type: `Identifier`,
name: `props`,
},
},
],
name: {
type: `JSXIdentifier`,
name: pageComponentName,
},
selfClosing: false,
},
closingElement: {
type: `JSXClosingElement`,
name: {
type: `JSXIdentifier`,
name: pageComponentName,
},
},
children: [
{
type: `JSXElement`,
openingElement: {
type: `JSXOpeningElement`,
attributes: [
{
type: `JSXSpreadAttribute`,
argument: {
type: `Identifier`,
name: `props`,
},
},
],
name: {
type: `JSXIdentifier`,
name: `GATSBY_COMPILED_MDX`,
},
selfClosing: true,
},
children: [],
},
],
},
},
],
},
},
} as unknown as ExportDefaultDeclaration)
})
if (!hasClassicReactImport) {
newBody.unshift({
type: `ImportDeclaration`,
specifiers: [
{
type: `ImportDefaultSpecifier`,
local: {
type: `Identifier`,
name: `React`,
},
},
],
source: {
type: `Literal`,
value: `react`,
},
})
}
AST.body = newBody
buildJsx(AST)
const transformedSource = generate(AST)
return transformedSource
} catch (error) {
reporter.panicOnBuild({
id: ERROR_CODES.InvalidAcornAST,
context: {
resourcePath: this.resourcePath,
mdxPath,
},
error,
})
return ``
}
}
export default gatsbyLayoutLoader