-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgatsby-node.js
174 lines (157 loc) · 5.26 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
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
const path = require('path');
const fs = require('fs-extra');
const ch = require('chalk');
const { createFilePath } = require('gatsby-source-filesystem');
const { siteMetadata: { title, version, defaultLanguage, supportedLanguages } } = require('./gatsby-config')
const activeEnv = process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || 'development';
require('dotenv').config({
path: `.env.${activeEnv}`,
});
const PATH_PREFIX = process.env.PATH_PREFIX || '';
// const PATH_PREFIX = `${__PATH_PREFIX__}/`;
const CREATE_ROOT_INDEX = 'true' === process.env.CREATE_ROOT_INDEX;
const STOP_WORDS = {};
supportedLanguages.forEach(lang => {
const fName = path.join(__dirname, `src/intl/stopwords-${lang}.json`);
STOP_WORDS[lang] = fs.existsSync(fName) ? require(fName) : [];
});
function getTextTokens(text, lang) {
text = text
// Remove URLS
.replace(/https?:[-/.\w?=#&%@]+/g, '')
// Remove ISO dates
.replace(/\d{4}-\d{2}-\d{2}T[-\w.:]+/g, '')
// Take symbols as separators
.replace(/[-_\s(){}[\]#*<>,.;:¿?/'@~=+\\|¡!"£$€^&`´]+/g, ' ')
// Convert all to lower case
.toLowerCase();
// Convert text to an array of unique words
const tokens = Array.from(new Set(text.split(' ')))
// Exclude stopwords and single chars
.filter(token => token.length > 1 && !STOP_WORDS[lang].includes(token))
// Sort list
.sort();
return tokens.join(' ').trim();
}
exports.onCreateNode = ({ node, getNode, actions: { createNodeField } }) => {
if (node.internal.type === 'Mdx') {
const path = createFilePath({ node, getNode });
let slug = path;
let lang = defaultLanguage;
const matches = path.match(/\/([a-z-_]*)\/$/);
if (matches && matches.length === 2) {
lang = matches[1];
slug = slug.substr(0, slug.length - lang.length - 1);
}
if (/\/content\/blog\//.test(node.fileAbsolutePath))
slug = `/blog${slug}`;
// Create node fields
createNodeField({
name: 'slug',
node,
value: slug,
});
createNodeField({
name: 'lang',
node,
value: lang,
});
createNodeField({
name: 'tokens',
node,
value: getTextTokens(node.rawBody, lang),
});
}
};
exports.createPages = async ({ graphql, actions: { createPage } }) => {
const result = await graphql(`
query {
allMdx(filter: {fields: {lang: {eq: "${defaultLanguage}"}}}, sort: {fields: frontmatter___date, order: DESC}) {
edges {
node {
parent {
... on File {
sourceInstanceName
}
}
fields {
lang
slug
}
frontmatter {
title
}
}
}
}
}
`);
if (result.errors) {
throw result.errors;
}
// Create info pages.
const pageTemplate = path.resolve('./src/templates/StaticPage.js');
const pages = result.data.allMdx.edges.filter(post => post.node.parent.sourceInstanceName === 'static');
pages.forEach(({ node: { fields: { slug } } }) => {
createPage({
path: slug,
component: pageTemplate,
context: {
slug,
},
});
});
// Create blog posts.
const blogPostTemplate = path.resolve('./src/templates/BlogPost.js');
const posts = result.data.allMdx.edges.filter(post => post.node.parent.sourceInstanceName === 'blog');
posts.forEach(({ node: { fields: { slug } } }, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node;
const next = index === 0 ? null : posts[index - 1].node;
createPage({
path: slug,
component: blogPostTemplate,
context: {
slug,
previous,
next,
},
});
});
};
// See: https://github.com/gatsbyjs/gatsby/issues/564#issuecomment-527891177
exports.onCreateWebpackConfig = ({ actions: { setWebpackConfig } }) => {
setWebpackConfig({
node: {
fs: 'empty',
net: 'empty',
}
})
};
// Move build files into the prefixed path, if defined
function moveBuildToPathPrefix() {
if (PATH_PREFIX && PATH_PREFIX.startsWith('/')) {
const buildDirName = 'public';
const buildDir = path.resolve(__dirname, buildDirName);
const prefix = `.${PATH_PREFIX}`;
const prefixedDir = path.resolve(__dirname, prefix);
if (fs.existsSync(prefixedDir)) {
console.log(`${ch.bold.red('error:')} directory "${prefixedDir}" alredy exists. Unable to move build files to "${PATH_PREFIX}"`);
return;
}
const destDir = path.resolve(__dirname, buildDirName, prefix);
fs.renameSync(buildDir, prefixedDir);
fs.moveSync(prefixedDir, destDir);
// Create a symlink for 404
fs.symlinkSync(`${prefix}/404.html`, `${buildDir}/404.html`);
console.log(`${ch.bold.green('info:')} Build files moved to "${destDir}"`);
if (CREATE_ROOT_INDEX) {
const rootIndexFile = path.resolve(buildDir, 'index.html');
const rootIndexContent = `<!doctype html><html lang="${defaultLanguage}"><head><title>${title}</title></head><body><a href=".${PATH_PREFIX}/index.html">${title} v${version}</a></body></html>`
fs.writeFileSync(rootIndexFile, rootIndexContent);
console.log(`${ch.bold.green('info:')} Created file "${rootIndexFile}"`);
}
}
}
exports.onPostBuild = async function onPostBuild() {
moveBuildToPathPrefix();
};