@jsverse/transloco-keys-manager
Version:
Extract translatable keys from projects that uses Transloco
85 lines • 3.61 kB
JavaScript
import { buildTranslationFiles } from '../keys-builder/index.js';
import { buildTranslationFile } from '../keys-builder/build-translation-file.js';
import { extractTemplateKeys } from '../keys-builder/template/index.js';
import { extractTSKeys } from '../keys-builder/typescript/index.js';
import { initExtraction } from '../utils/init-extraction.js';
import { mergeDeep } from '../utils/object.utils.js';
import { buildScopeFilePaths } from '../utils/path.utils.js';
import { resolveConfig } from '../utils/resolve-config.js';
import { updateScopesMap } from '../utils/update-scopes-map.js';
import { generateKeys } from './generate-keys.js';
let init = true;
export class TranslocoExtractKeysWebpackPlugin {
config;
constructor(inlineConfig = {}) {
this.config = resolveConfig(inlineConfig);
}
apply(compiler) {
compiler.hooks.watchRun.tapPromise('TranslocoExtractKeysPlugin', async (comp) => {
if (init) {
init = false;
return buildTranslationFiles(this.config);
}
const keysExtractions = {
html: [],
ts: [],
};
const files = comp.modifiedFiles ||
Object.keys(comp.watchFileSystem.watcher.mtimes);
for (const file of files) {
const fileType = resolveFileType(file);
if (fileType) {
keysExtractions[fileType].push(file);
}
}
if (keysExtractions.html.length || keysExtractions.ts.length) {
let htmlResult = initExtraction();
let tsResult = initExtraction();
if (keysExtractions.ts.length) {
// Maybe someone added a TRANSLOCO_SCOPE
const newScopes = updateScopesMap({ files: keysExtractions.ts });
const paths = buildScopeFilePaths({
aliasToScope: newScopes,
langs: this.config.langs,
output: this.config.output,
fileFormat: this.config.fileFormat,
});
paths.forEach(({ path }) => buildTranslationFile({
path,
fileFormat: this.config.fileFormat,
}));
tsResult = extractTSKeys({
...this.config,
files: keysExtractions.ts,
});
}
if (keysExtractions.html.length) {
htmlResult = extractTemplateKeys({
...this.config,
files: keysExtractions.html,
});
}
const scopeToKeys = mergeDeep({}, htmlResult.scopeToKeys, tsResult.scopeToKeys);
const hasTranslateKeys = Object.keys(scopeToKeys).some((key) => Object.keys(scopeToKeys[key]).length > 0);
if (hasTranslateKeys) {
generateKeys({
config: this.config,
translationPath: this.config.translationsPath,
scopeToKeys,
});
}
}
return Promise.resolve();
});
}
}
function resolveFileType(file) {
return isHtml(file) ? 'html' : isTs(file) ? 'ts' : null;
}
function isHtml(file) {
return file.endsWith('.html');
}
function isTs(file) {
return file.endsWith('.ts') && !file.endsWith('.spec.ts');
}
//# sourceMappingURL=webpack-plugin.js.map