-
-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathcreateMessagesDeclaration.tsx
More file actions
95 lines (80 loc) · 2.53 KB
/
createMessagesDeclaration.tsx
File metadata and controls
95 lines (80 loc) · 2.53 KB
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
import fs from 'fs';
import path from 'path';
import {throwError} from './utils.js';
import watchFile from './watchFile.js';
function runOnce(fn: () => void) {
if (process.env._NEXT_INTL_COMPILE_MESSAGES === '1') {
return;
}
process.env._NEXT_INTL_COMPILE_MESSAGES = '1';
fn();
}
export default function createMessagesDeclaration(
messagesPaths: Array<string>
) {
const shouldRun = [
'dev',
'build',
'typegen'
// Note: The 'lint' task doesn't consult the
// Next.js config, so we can't detect it here.
].some((arg) => process.argv.includes(arg));
if (!shouldRun) {
return;
}
// Next.js can call the Next.js config multiple
// times - ensure we only run once.
runOnce(() => {
for (const messagesPath of messagesPaths) {
const fullPath = path.resolve(messagesPath);
if (!fs.existsSync(fullPath)) {
throwError(
`\`createMessagesDeclaration\` points to a non-existent file: ${fullPath}`
);
}
if (!fullPath.endsWith('.json')) {
throwError(
`\`createMessagesDeclaration\` needs to point to a JSON file. Received: ${fullPath}`
);
}
// Keep this as a runtime check and don't replace
// this with a constant during the build process
const env = process.env['NODE_ENV'.trim()];
compileDeclaration(messagesPath);
if (env === 'development') {
startWatching(messagesPath);
}
}
});
}
function startWatching(messagesPath: string) {
const watcher = watchFile(messagesPath, () => {
compileDeclaration(messagesPath, true);
});
process.on('exit', () => {
watcher.close();
});
}
function compileDeclaration(messagesPath: string, async: true): Promise<void>;
function compileDeclaration(messagesPath: string, async?: false): void;
function compileDeclaration(
messagesPath: string,
async = false
): void | Promise<void> {
const declarationPath = messagesPath.replace(/\.json$/, '.d.json.ts');
function createDeclaration(content: string) {
return `// This file is auto-generated by next-intl, do not edit directly.
// See: https://next-intl.dev/docs/workflows/typescript#messages-arguments
declare const messages: ${content.trim()};
export default messages;`;
}
if (async) {
return fs.promises
.readFile(messagesPath, 'utf-8')
.then((content) =>
fs.promises.writeFile(declarationPath, createDeclaration(content))
);
}
const content = fs.readFileSync(messagesPath, 'utf-8');
fs.writeFileSync(declarationPath, createDeclaration(content));
}