Skip to content

Commit

Permalink
feat(parser): Add exception filter for removing unused keys
Browse files Browse the repository at this point in the history
  • Loading branch information
yocarbo committed Oct 4, 2024
1 parent f720314 commit 56675a2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,7 @@ Below are the configuration options with their default values:
compatibilityJSON: 'v3', // One of: 'v1', 'v2', 'v3', 'v4
debug: false,
removeUnusedKeys: false,
filterUnusedKeys: false,
sort: false,
attr: {
list: ['data-i18n'],
Expand Down Expand Up @@ -574,6 +575,28 @@ Type: `Boolean` Default: `false`

Set to `true` to remove unused translation keys from i18n resource files.

#### filterUnusedKeys

Type: `Object` Default: `false`

If an `Object` is supplied and `removeUnusedKeys` is set to `true`, to leave specific keys you can specify a function like so:
```js
filterUnusedKeys: ({ lng, ns, unusedKey }) => {
if (ns === 'resource') {
const exceptionKeys = ['word', 'key.word', ...];
if (exceptionKeys.includes(unusedKey)) {
// leave key
return true;
}
}
if (ns === 'other_resource') {
// leave key
return true;
}
// remove key
return false;
}

#### sort

Type: `Boolean` Default: `false`
Expand Down
34 changes: 32 additions & 2 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -796,10 +796,40 @@ class Parser {
const resStoreKeys = flattenObjectKeys(_.get(this.resStore, [lng, ns], {}));
const resScanKeys = flattenObjectKeys(_.get(this.resScan, [lng, ns], {}));
const unusedKeys = _.differenceWith(resStoreKeys, resScanKeys, _.isEqual);
let filteredKey;

for (let i = 0; i < unusedKeys.length; ++i) {
_.unset(resMerged[lng][ns], unusedKeys[i]);
this.log(`Removed an unused translation key { ${chalk.red(JSON.stringify(unusedKeys[i]))} from ${chalk.red(JSON.stringify(this.formatResourceLoadPath(lng, ns)))}`);
filteredKey = false;

if (
this.options.filterUnusedKeys &&
typeof this.options.filterUnusedKeys === 'function'
) {
filteredKey = this.options.filterUnusedKeys({
lng,
ns,
unusedKey: unusedKeys[i].toString().replaceAll(',', '.'),
});
}

if (!filteredKey) {
_.unset(resMerged[lng][ns], unusedKeys[i]);
this.log(
`Removed an unused translation key { ${chalk.red(
JSON.stringify(unusedKeys[i])
)} } from ${chalk.red(
JSON.stringify(this.formatResourceLoadPath(lng, ns))
)}`
);
continue;
}
this.log(
`Skipped removing an unused translation key { ${chalk.yellow(
JSON.stringify(unusedKeys[i])
)} } from ${chalk.yellow(
JSON.stringify(this.formatResourceLoadPath(lng, ns))
)}`
);
}

// Omit empty object
Expand Down

0 comments on commit 56675a2

Please sign in to comment.