81 lines
2.3 KiB
JavaScript
81 lines
2.3 KiB
JavaScript
const path = require('path');
|
|
const fs = require('node:fs');
|
|
|
|
const { Liquid } = require('liquidjs');
|
|
|
|
const languages = [
|
|
{ code: 'fr', name: 'Français' },
|
|
{ code: 'en', name: 'English' }
|
|
];
|
|
const defaultLanguage = 'en';
|
|
const source = ['run-test.html', 'result.html'];
|
|
const i18nDir = 'i18n';
|
|
const distDir = 'dist';
|
|
const static = 'static';
|
|
const baseUrl = '/';
|
|
|
|
const engine = new Liquid({
|
|
root: [path.resolve(__dirname, 'views/'), path.resolve(__dirname, 'views/partials')] ,
|
|
});
|
|
|
|
function render(files, context, cb) {
|
|
for (const file of source) {
|
|
const html = engine.renderFileSync(file, context);
|
|
cb && cb(file, html);
|
|
}
|
|
}
|
|
|
|
async function build() {
|
|
fs.mkdirSync(distDir, {recursive: true});
|
|
fs.cpSync(static, `${distDir}/${static}`, {recursive: true});
|
|
|
|
for (const lang of languages) {
|
|
let locales = JSON.parse(fs.readFileSync(`${i18nDir}/${lang.code}.json`, 'utf8'));
|
|
|
|
function translate(string) {
|
|
return locales[string] || string;
|
|
}
|
|
|
|
function staticUrl(path) {
|
|
return `${baseUrl}static/${path}`
|
|
}
|
|
|
|
function localizedUrl(path) {
|
|
return `${baseUrl}${lang.code}/${path}`
|
|
}
|
|
|
|
engine.registerFilter('tr', translate);
|
|
engine.registerFilter('staticUrl', staticUrl);
|
|
engine.registerFilter('localizedUrl', localizedUrl);
|
|
|
|
fs.mkdirSync(`${distDir}/${lang.code}`, {recursive: true});
|
|
|
|
await render(source, { lang, languages, baseUrl }, (file, html) => fs.writeFileSync(`${distDir}/${lang.code}/${file}`, html));
|
|
}
|
|
}
|
|
|
|
async function i18nExtract() {
|
|
const strings = {};
|
|
|
|
const [ lang ] = [...languages.filter(l => l.code === defaultLanguage), ...languages];
|
|
|
|
function collectStrings( string ) {
|
|
strings[string] = string;
|
|
return string;
|
|
}
|
|
|
|
engine.registerFilter('tr', collectStrings);
|
|
|
|
await render(source, { lang, languages, baseUrl });
|
|
|
|
fs.writeFileSync(`${i18nDir}/source.json`, JSON.stringify(strings, null, 4) + '\n');
|
|
|
|
for (const lang of languages) {
|
|
let locales = JSON.parse(fs.readFileSync(`${i18nDir}/${lang.code}.json`, 'utf8'));
|
|
fs.writeFileSync(`${i18nDir}/${lang.code}.json`, JSON.stringify({...strings, ...locales}, null, 4) + '\n');
|
|
}
|
|
}
|
|
|
|
build();
|
|
//i18nExtract();
|