-
Notifications
You must be signed in to change notification settings - Fork 26
/
gatsby-node.js
87 lines (70 loc) · 2.11 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
81
82
83
84
85
86
87
import fsp from 'fs/promises';
import robotsTxt from 'generate-robotstxt';
import path from 'path';
const publicPath = './public';
const defaultEnv = 'development';
const defaultOptions = {
output: '/robots.txt',
query: `{
site {
siteMetadata {
siteUrl
}
}
}`
};
function runQuery(handler, query) {
return handler(query).then(res => {
if (res.errors) {
throw new Error(res.errors.join(', '));
}
return res.data;
});
}
const getOptions = pluginOptions => {
const options = { ...pluginOptions };
delete options.plugins;
const { env = {}, resolveEnv = () => process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV } = options;
const envOptions = env[resolveEnv()] || env[defaultEnv] || {};
delete options.env;
delete options.resolveEnv;
return { ...options, ...envOptions };
};
export async function onPostBuild({ graphql, pathPrefix = "" }, pluginOptions) {
const userOptions = getOptions(pluginOptions);
const mergedOptions = { ...defaultOptions, ...userOptions };
if(mergedOptions.host !== null) {
if (
!Object.prototype.hasOwnProperty.call(mergedOptions, 'host')
) {
const {
site: {
siteMetadata: { siteUrl }
}
} = await runQuery(graphql, mergedOptions.query);
mergedOptions.host = siteUrl;
}
}
if(mergedOptions.sitemap !== null) {
if (
!Object.prototype.hasOwnProperty.call(mergedOptions, 'sitemap')
) {
mergedOptions.sitemap = new URL(path.posix.join(pathPrefix, 'sitemap-index.xml'), mergedOptions.host).toString();
} else {
try {
new URL(mergedOptions.sitemap)
} catch {
mergedOptions.sitemap = new URL(mergedOptions.sitemap.startsWith(pathPrefix) ? mergedOptions.sitemap : path.posix.join(pathPrefix, mergedOptions.sitemap), mergedOptions.host).toString()
}
}
}
const { policy, sitemap, host, output, configFile } = mergedOptions;
const content = await robotsTxt({
policy,
sitemap,
host,
configFile
});
const filename = path.join(publicPath, output);
return fsp.writeFile(path.resolve(filename), content);
}