-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-node.js
80 lines (68 loc) · 2.1 KB
/
gatsby-node.js
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
"use strict"
const fs = require(`fs`)
const { extname, resolve } = require(`path`)
const recursiveReaddir = require(`recursive-readdir-synchronous`)
const normalizePath = require(`normalize-path`)
const {
OPTION_DEFAULT_LINK_TEXT,
OPTION_DEFAULT_HTML,
OPTION_DEFAULT_REDIRECT_TEMPLATE_PATH,
} = require(`./constants`)
exports.createPages = (
{ actions },
{
directory = OPTION_DEFAULT_LINK_TEXT,
externals = [],
html = OPTION_DEFAULT_HTML,
redirectTemplate = OPTION_DEFAULT_REDIRECT_TEMPLATE_PATH,
} = {}
) => {
if (!directory.endsWith(`/`)) {
directory += `/`
}
const { createPage } = actions
if (!fs.existsSync(directory)) {
throw Error(`Invalid REPL directory specified: "${directory}"`)
}
if (!fs.existsSync(redirectTemplate)) {
throw Error(
`Invalid REPL redirectTemplate specified: "${redirectTemplate}"`
)
}
// TODO We could refactor this to use 'recursive-readdir' instead,
// And wrap with Promise.all() to execute createPage() in parallel.
// I'd need to find a way to reliably test error handling though.
const files = recursiveReaddir(directory)
if (files.length === 0) {
console.warn(`Specified REPL directory "${directory}" contains no files`)
return
}
files.forEach(file => {
if (extname(file) === `.js` || extname(file) === `.jsx`) {
const slug = file
.substring(0, file.length - extname(file).length)
.replace(new RegExp(`^${directory}`), `redirect-to-codepen/`)
const code = fs.readFileSync(file, `utf8`)
// Codepen configuration.
// https://blog.codepen.io/documentation/api/prefill/
const action = `https://codepen.io/pen/define`
const payload = JSON.stringify({
editors: `0010`,
html,
js: code,
js_external: externals.join(`;`),
js_pre_processor: `babel`,
layout: `left`,
})
createPage({
path: slug,
// Normalize the path so tests pass on Linux + Windows
component: normalizePath(resolve(redirectTemplate)),
context: {
action,
payload,
},
})
}
})
}