-
Notifications
You must be signed in to change notification settings - Fork 178
/
gatsby-node.js
106 lines (95 loc) · 2.77 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
const webpack = require("webpack")
function flattenMessages(nestedMessages, prefix = "") {
return Object.keys(nestedMessages).reduce((messages, key) => {
let value = nestedMessages[key]
let prefixedKey = prefix ? `${prefix}.${key}` : key
if (typeof value === "string") {
messages[prefixedKey] = value
} else {
Object.assign(messages, flattenMessages(value, prefixedKey))
}
return messages
}, {})
}
exports.onCreateWebpackConfig = ({ actions, plugins }, pluginOptions) => {
const { redirectComponent = null, languages, defaultLanguage } = pluginOptions
if (!languages.includes(defaultLanguage)) {
languages.push(defaultLanguage)
}
const regex = new RegExp(languages.map((l) => l.split("-")[0]).join("|"))
actions.setWebpackConfig({
plugins: [
plugins.define({
GATSBY_INTL_REDIRECT_COMPONENT_PATH: JSON.stringify(redirectComponent),
}),
new webpack.ContextReplacementPlugin(
/@formatjs[/\\]intl-relativetimeformat[/\\]dist[/\\]locale-data$/,
regex
),
new webpack.ContextReplacementPlugin(
/@formatjs[/\\]intl-pluralrules[/\\]dist[/\\]locale-data$/,
regex
),
],
})
}
exports.onCreatePage = async ({ page, actions }, pluginOptions) => {
//Exit if the page has already been processed.
if (typeof page.context.intl === "object") {
return
}
const { createPage, deletePage } = actions
const {
path = ".",
languages = ["en"],
defaultLanguage = "en",
redirect = false,
} = pluginOptions
const getMessages = (path, language) => {
try {
// TODO load yaml here
const messages = require(`${path}/${language}.json`)
return flattenMessages(messages)
} catch (error) {
if (error.code === "MODULE_NOT_FOUND") {
process.env.NODE_ENV !== "test" &&
console.error(
`[gatsby-plugin-intl] couldn't find file "${path}/${language}.json"`
)
}
throw error
}
}
const generatePage = (routed, language) => {
const messages = getMessages(path, language)
const newPath = routed ? `/${language}${page.path}` : page.path
return {
...page,
path: newPath,
context: {
...page.context,
language,
intl: {
language,
languages,
messages,
routed,
originalPath: page.path,
redirect,
defaultLanguage,
},
},
}
}
const newPage = generatePage(false, defaultLanguage)
deletePage(page)
createPage(newPage)
languages.forEach((language) => {
const localePage = generatePage(true, language)
const regexp = new RegExp("/404/?$")
if (regexp.test(localePage.path)) {
localePage.matchPath = `/${language}/*`
}
createPage(localePage)
})
}