New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

i18n-unused

Package Overview
Dependencies
Maintainers
0
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

i18n-unused

The tool for finding, analyzing and removing unused and missed i18n translations in your JavaScript project

  • 0.17.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
18K
increased by2.07%
Maintainers
0
Weekly downloads
 
Created
Source

i18n-unused

npm npm

The static analyze tool for finding, marking and removing unused and missing i18n translations in your JavaScript project.

Installation

With npm:

npm install --save-dev i18n-unused

With yarn:

yarn add --dev i18n-unused

Configuration

Add config i18n-unused.config.js to your root folder:

/** @type {import('i18n-unused').RunOptions} */
module.exports = {
  localesPath: 'src/locales',
  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
Description
RequiredType
Default value
localesPathpath to search for localesyesstring-
localesExtensionsallowed file extensions for localesnostring[]if not set localeNameResolver: ['json']
localeNameResolverfile name resolver for localesnoRegExp, (name: string) => boolean-
customCheckerfunction to check if a key is used, if so the key should be removed from translationsKeysnofn, (matchedKeys: Set<string>, translationsKeys: string[] => void)A defined validations will be applied
localeFileParserresolve locale imports, for example if you use named imports from locales files, just wrap it to your own resolverno(module) => modulefn, return module.default or module
localeFileLoaderload the locale file manually (e.g. for using your own parser)no(filePath) => object-
srcPathpath to search for translationsnostring'' (same as run folder)
srcExtensionsallowed file extensions for translationsnostring[]['js', 'ts', 'jsx', 'tsx', 'vue']
ignorePathsignored paths, eg: ['src/ignored-folder'], should start similarly srcPathnostring[]-
translationKeyMatchermatcher to search for translation keys in filesnoRegExpRegExp, match $_, $t, t, $tc, tc and i18nKey
excludeKeydoesn't process translations that include passed key(s), for example if you set excludeKey: '.props.', script will ignore Button.props.value.nostring, string[]-
ignoreCommentsIgnore code comments in src files.nobooleanfalse
markerspecial string to mark unused translations, it'll added via mark-unusednostring'[UNUSED]'
gitCheckshow git state change treenobooleanfalse
contextuse i18n context, (eg: plurals)nobooleantrue
flatTranslationsuse flat translations, (eg: Flat JSON)nobooleanfalse
translationSeparatorseparator for translations using in codenostring'.'
translationContextSeparatorseparator for i18n context (see context option)nostring'_'
translationContextMatchermatcher to search for context endingsnoRegExpRegExp, match zero, one, two, few, many, other, male, female, 0, 1, 2, 3, 4, 5, plural, 11 and 100
missedTranslationParserparser for ejecting value from translationKeyMatcher matchesnoRegExp, (v: string) => stringRegExp, match value inside rounded brackets
localeJsonStringifyIndentjson indent value for writing json file, either a number of spaces, or a string to indent with. (i.e. 2, 4, \t)nostring , number2

Usage

Get help:

i18n-unused -h

Display unused translations:

i18n-unused display-unused

Display unused translations for mashpie/i18n-node:

i18n-unused display-unused --translation-key-matcher '/(?:[$ .](__))\(.*?\)/gi'

Mark unused translations via [UNUSED] or marker from config (works only with json for now):

i18n-unused mark-unused

Remove unused translations (works only with json for now):

i18n-unused remove-unused

Sync translations (works only with json for now):

i18n-unused sync <source> <target>

Display missed translations:

i18n-unused display-missed

Usage in code

collectUnusedTranslations

If you use tool in code, you can run async function collectUnusedTranslations:

import { collectUnusedTranslations } from 'i18n-unused';

const handleTranslations = async () => {
  const unusedTranslations = await collectUnusedTranslations(
    localesPaths, // paths to locale files
    srcFilesPaths, // paths to src files
    {
      localeFileParser: (module) => module, // optional, resolver for module
      excludeTranslationKey: ['.props.'], // optional, special string or sting[] to exclude flat translations
    },
  );
};

It'll return to you follow collect:

{
  translations: [
    {
      localePath: 'locale_file_path',
      keys: ['unused_key'],
      count: 1,
    },
  ],
  totalCount: 1,
}

collectMissedTranslations

If you use tool in code, you can run async function collectMissedTranslations:

import { collectMissedTranslations } from 'i18n-unused';

const handleTranslations = async () => {
  const missedTranslations = await collectMissedTranslations(
    localesPaths, // paths to locale files
    srcFilesPaths, // paths to src files
    {
      localeFileParser: (module) => module, // optional, resolver for module
      excludeTranslationKey: ['.props.'], // optional, special string or sting[] to exclude flat translations
      translationKeyMatcher: /(?:[$ .](_|t|tc))\(.*?\)/ig, // optional, match translation keys in files
    },
  );
};

You'll get the following collection:

{
  translations: [
    {
      filePath: 'src_file_path',
      staticKeys: ['missed_key'], // keys without ${} syntax
      dynamicKeys: ['missed_key'], // keys with ${} syntax
      staticCount: 1,
      dynamicCount: 1,
    },
  ],
  totalStaticCount: 1,
  totalDynamicCount: 1,
}

generateFilesPaths

Available as async function generateFilesPaths:

import { generateFilesPaths } from 'i18n-unused';

const handleFilesPaths = async () => {
  // return array of full paths to files
  const filesPaths = await generateFilesPaths(
    srcPath, // path where search files, example: 'src/locales'
    {
      srcExtensions, // allowed file extensions, example: ['js', 'ts']
      fileNameResolver, // resolver for file name, see more info about 'localeNameResolver' option
    },
  );
};

Action results

Next actions return unusedTranslations:

  • displayUnusedTranslations
  • removeUnusedTranslations
  • markUnusedTranslations

Next actions return missedTranslations:

  • displayMissedTranslations

What else?

If the tool helped you, please rate it on github, thx. I'll be glad to your PRs =)

License

MIT License. Maxim Vishnevsky

Keywords

FAQs

Package last updated on 25 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc