Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESM support + Easier way to specify translationKeyMatcher #31

Merged
merged 3 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ module.exports = {
srcPath: 'src',
};
```
For ES-Modules (esm) use `i18n-unused.config.cjs`. You can also use the `.json` with no support for callbacks.

### Configuration options

| Option name | <div style="width: 280px">Description</div> | Required | Type | <div style="min-width: 100px">Default value</div> |
Expand All @@ -39,7 +41,7 @@ module.exports = {
| srcPath | path to search for translations | no | string | `''` (same as run folder)
| srcExtensions | allowed file extensions for translations | no | string[] | ['js', 'ts', 'jsx', 'tsx', 'vue']
| ignorePaths | ignored paths, eg: `['src/ignored-folder']`, should start similarly `srcPath` | no | string[] | -
| translationKeyMatcher | matcher to searching for translation keys in files | no | RegExp | RegExp, match `$_`, `$t`, `t`, `$tc`, `tc` and `i18nKey`
| translationKeyMatcher | matcher to search for translation keys in files | no | RegExp | RegExp, match `$_`, `$t`, `t`, `$tc`, `tc` and `i18nKey`
| excludeKey | doesn't process translations that include passed key(s), for example if you set `excludeKey: '.props.'`, script will ignore `Button.props.value`. | no | string, string[] | -
| ignoreComments | Ignore code comments in src files. | no | boolean | false
| marker | special string to mark unused translations, it'll added via `mark-unused` | no | string | '[UNUSED]'
Expand All @@ -63,6 +65,12 @@ Display unused translations:
i18n-unused display-unused
```

Display unused translations for [mashpie/i18n-node](https://github.com/mashpie/i18n-node):
```bash
i18n-unused display-unused --translation-key-matcher '/(?:[$ .](__))\(.*?\)/gi'
```


Mark unused translations via `[UNUSED]` or marker from config (works only with `json` for now):
```bash
i18n-unused mark-unused
Expand Down
4 changes: 4 additions & 0 deletions bin/i18n-unused.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@ const {
removeUnusedTranslations,
markUnusedTranslations,
syncTranslations,
parseRegex
} = require('../dist/i18n-unused.cjs');



program.description(description);

program.version(version, '-v --version', 'output version');

program
.option('-sExt, --src-extensions [srcExtensions...]', 'files extensions, which includes for searching (ext ext ext; by default: js, ts, jsx, tsx, vue)')
.option('-lExt, --locales-extensions [localesExtensions...]', 'locales files extensions (ext,ext,ext; by default: json)')
.option('-lExt, --translation-key-matcher <translationKeyMatcher>', '{string} locales matcher to search for translation keys in files by default: \'/(?:[$ .](_|t|tc|i18nKey))\\(.*?\\)/gi\'', parseRegex)
.option('-sPath, --src-path <srcPath>', 'path to source of code (path, ex. \'src\')')
.option('-lPath, --locales-path <localesPath>', 'path to locales (path, ex. \'src/locales\')');

Expand Down
31 changes: 26 additions & 5 deletions src/core/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { resolveFile } from '../helpers/files';

import { RunOptions, RecursiveStruct } from '../types';
import fs from "fs";
import {parseRegex} from "../helpers/parseRegex";

const defaultValues: RunOptions = {
srcPath: '',
Expand All @@ -27,12 +29,31 @@ export const initialize = async (
let config: RunOptions = { ...inlineOptions };

try {
const configFile = await resolveFile(
`${process.cwd()}/i18n-unused.config.js`,
);
const base = process.cwd();

config = { ...configFile, ...inlineOptions };
} catch (e) {}
let configFile: Partial<RunOptions> = {};

for (const ext of ["js", "cjs", "json"]) {
const path = `${base}/i18n-unused.config.${ext}`;
if (fs.existsSync(path)) {
configFile = await resolveFile(path);
// ⛔ There is no safe/reliable way to parse a function
// ✔ When the file is a JSON need to parse the regex
if (ext === "json") {
const potentialRegex = ["translationKeyMatcher", "missedTranslationParser", "localeNameResolver"];
potentialRegex.forEach(value => {
if (Object.prototype.hasOwnProperty.call(configFile, value)) {
configFile[value] = parseRegex(configFile[value]);
}
});
}
break;
}
}

config = {...configFile, ...inlineOptions};
} catch (e) {
}

if (!config.localesPath) {
throw new Error('Locales path is required');
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const resolveFile = async (
m = loader(filePath);
} else if (ext === 'ts') {
m = await tsImport.compile(filePath);
} else if (ext === 'js') {
} else if (["js", "cjs"].includes(ext)) {
let r = createRequire(importMetaUrl());
r = r('esm')(m /*, options*/);
m = r(filePath);
Expand Down
9 changes: 9 additions & 0 deletions src/helpers/parseRegex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Transform the escaped string provided into a valid regex
* @param {string} str
* @return {RegExp}
*/
export const parseRegex = (str) => {
const parts = str.split("/");
return new RegExp(`${parts[1]}`.replace(/\\\\/g, "\\"), parts[2]);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { syncTranslations } from './actions/sync';

export { collectUnusedTranslations } from './core/translations';
export { generateFilesPaths } from './helpers/files';
export { parseRegex } from './helpers/parseRegex';