next-intl
Version:
Internationalization (i18n) for Next.js
61 lines (56 loc) • 2.06 kB
JavaScript
import fs from 'fs';
import path from 'path';
import { throwError } from './utils.js';
import watchFile from './watchFile.js';
function runOnce(fn) {
if (process.env._NEXT_INTL_COMPILE_MESSAGES === '1') {
return;
}
process.env._NEXT_INTL_COMPILE_MESSAGES = '1';
fn();
}
function createMessagesDeclaration(messagesPaths) {
// 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) {
const watcher = watchFile(messagesPath, () => {
compileDeclaration(messagesPath, true);
});
process.on('exit', () => {
watcher.close();
});
}
function compileDeclaration(messagesPath, async = false) {
const declarationPath = messagesPath.replace(/\.json$/, '.d.json.ts');
function createDeclaration(content) {
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));
}
export { createMessagesDeclaration as default };