Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
@hishprorg/commodi-distinctio-alias
Advanced tools
**A fully type-safe and lightweight internationalization library for all your TypeScript and JavaScript projects.**
A fully type-safe and lightweight internationalization library for all your TypeScript and JavaScript projects.
:baby_chick: lightweight (~1kb)
:ok_hand: easy to use syntax
:running: fast and efficient
:safety_vest: prevents you from making mistakes (also in plain JavaScript projects)
:construction_worker: creates boilerplate code for you
:speech_balloon: supports plural rules
:date: allows formatting of values e.g. locale-dependent date or number formats
:left_right_arrow: supports switch-case statements e.g. for gender-specific output
:arrow_down: option for asynchronous loading of locales
:books: supports multiple namespaces
:stopwatch: supports SSR (Server-Side Rendering)
:handshake: can be used for frontend, backend and API projects
:mag: locale-detection for browser and server environments
:arrows_counterclockwise: import and export translations from/to files or services
:no_entry: no external dependencies
Click here to see an interactive demo of @hishprorg/commodi-distinctio-alias
showing some key aspects of the type-checking capabilities of this internationalization library.
@hishprorg/commodi-distinctio-alias
to your project@hishprorg/commodi-distinctio-alias
add to your bundle size@hishprorg/commodi-distinctio-alias
implemented:keyboard: Run the setup process and automatically detect the config needed
npx @hishprorg/commodi-distinctio-alias --setup-auto
or manually configure @hishprorg/commodi-distinctio-alias
by answering a few questions
npx @hishprorg/commodi-distinctio-alias --setup
It didn't work? See here for possible troubleshooting.
:eyes: Take a look at the generated files and it's folder-structure after running npm run @hishprorg/commodi-distinctio-alias
(or npx @hishprorg/commodi-distinctio-alias
)
:open_book: Explore the assets
@hishprorg/commodi-distinctio-alias
offers a lot. Just presscmd + F
to search on this page or see the table of contents that will link you to more specific subpages with more details.
:star: Star this project on GitHub
Thanks! This helps the project to grow.
Having trouble setting up @hishprorg/commodi-distinctio-alias
? Reach out to us via Github Discussions or on Discord.
npm install @hishprorg/commodi-distinctio-alias
The changelog of this project can be found here
5.x.x
: see the release post
4.x.x
: see the release post
3.x.x
: see the release post
Curious about what comes next? See this discussion to learn more about the plans for the future of this project.
If you would like to get involved within this project, take a look at this discussion.
The package can be used inside JavaScript and TypeScript applications. You will get a lot of benefits by running the generator since it will create a few wrappers to provide you with full typesafety.
You can use @hishprorg/commodi-distinctio-alias
in a variety of project-setups:
All you need is inside the generated file i18n-util.ts
. You can use the functions in there to create a small wrapper for your application.
Feel free to open a new discussion if you need a guide for a specific framework.
See here if you want to learn how you can use @hishprorg/commodi-distinctio-alias
to implement your own specific use-case.
The library should work in all modern browsers. It uses some functionality from the Intl
namespace. You can see the list of supported browsers here. If you want to support older browsers that don't include these functions, you would need to include a polyfill like intl-pluralrules.
If you want to get the best typesafety features, you will need to use the generator
in order to create types and boilerplate code for you
Here you can see some examples where @hishprorg/commodi-distinctio-alias
can help you:
The @hishprorg/commodi-distinctio-alias
package allows us to be 100% typesafe for our translation functions and even the translations for other locales itself. The generator
outputs TypeScript definitions based on your base locale.
You will also benefit from full typesafe JavaScript code via JSDoc-annotations.
@hishprorg/commodi-distinctio-alias
comes with an API that allows other services to read and update translations. You can connect other services by using the importer
and exporter
functionality.
There also exists an official plugin for Inlang. It allows you to use @hishprorg/commodi-distinctio-alias
together with the tooling Inlang provides. You can find it here.
The footprint of the @hishprorg/commodi-distinctio-alias
package is smaller compared to other existing i18n packages. Most of the magic happens in development mode, where the generator creates TypeScript definitions for your translations. This means, you don't have to ship the whole package to your users. The only two parts, that are needed in production are:
These parts are bundled into the core functions. The sizes of the core functionalities are:
Apart from that there can be a small overhead depending on which utilities and wrappers you use.
There also exists a useful wrapper for some frameworks:
@hishprorg/commodi-distinctio-alias
angular-service: 1230 bytes gzipped@hishprorg/commodi-distinctio-alias
react-context: 1602 bytes gzipped@hishprorg/commodi-distinctio-alias
solid-context: 1403 bytes gzipped@hishprorg/commodi-distinctio-alias
svelte-store: 1342 bytes gzipped@hishprorg/commodi-distinctio-alias
vue-plugin: 1256 bytes gzippedThe package was optimized for performance:
If you use @hishprorg/commodi-distinctio-alias
you will get a smaller bundle compared to other i18n solutions. But that doesn't mean, we should stop there. There are some possible optimizations planned to decrease the bundle size even further.
Become a sponsor :heart: if you want to support my open source contributions.
Thanks for sponsoring my open source work!
Dou you still have some questions? Reach out to us via Github Discussions or on Discord.
LL.key()
renders an empty stringYou probably forgot to load the locale first before using it. Calling loadLocaleAsync('en')
or loadAllLocales()
will fix it.
@hishprorg/commodi-distinctio-alias
failsRunning the npx
command with a npm
version <7.0.0
will probably fail because it will not include peerDependencies
.
You could try installing it locally via:
npm install @hishprorg/commodi-distinctio-alias
and then run the setup-command from within the node_modules
folder via:
./node_modules/@hishprorg/commodi-distinctio-alias/cli/@hishprorg/commodi-distinctio-alias.mjs --setup-auto
here is the original issue with some additional information: #142
Property 'XYZ' does not exist on type 'TranslationFunctions'
Make sure to run the generator after you make changes to your base translation file. The generator will generate and update the types for you.
@hishprorg/commodi-distinctio-alias
inside JavaScript applications?Yes, you can. See the usage section for instructions. Even if you don't use TypeScript you can still improve from some typesafety features via JSDoc-annotations.
The generator will only look for changes in your base locale file. Make sure to always update your base locale file first, in order to get the correct auto-generated types. If you want to change your base locale file, make sure to give it the type of BaseTranslation
. All other locales should have the type of Translation
. E.g. if you set your base locale to italian, you would need to do it like this:
set your base locale to italian (it
) in ´.@hishprorg/commodi-distinctio-alias.json`:
{
"baseLocale": "it"
}
define the type of your base locale as BaseTranslation
// file 'src/i18n/it/index.ts'
import type { BaseTranslation } from '../i18n-types'
const it: BaseTranslation = {
WELCOME: "Benvenuto!"
}
export default it
define the type of your other locales as Translation
// file 'src/i18n/en/index.ts'
import type { Translation } from '../i18n-types'
const en: Translation = {
WELCOME: "Welcome!"
}
export default en
The generator creates some helpful wrappers for you. If you want to write your own wrappers, you can disable the generation of these files by setting the generateOnlyTypes
option to true
.
@hishprorg/commodi-distinctio-alias
supported by i18n-ally
?Yes, you can configure i18n-ally
like this. There is currently also an open PR
that will add official support for @hishprorg/commodi-distinctio-alias
.
When you want to dynamically access a translation, you can use the usual JavaScript syntax to access a property via a variable (myObject[myVariable]
).
// i18n/en.ts
import type { BaseTranslation } from '../i18n-types'
const en: BaseTranslation = {
category: {
simple: {
title: 'Simple title',
description: 'I am a description for the "simple" category',
},
advanced: {
title: 'Advanced title',
description: 'I am a description for the "advanced" category',
}
}
}
export default en
<script lang="ts">
// Component.svelte
import LL from '$i18n/i18n-svelte'
import type { Translation } from '$i18n/i18n-types'
// ! do not type it as `string`
// by restricting the type, you don't loose the typesafety features
export let category: keyof Translation['category'] = 'simple'
</script>
<h2>{$LL.category[category].title()}
<p>
{$LL.category[category].description()}
<p>
Validation libraries like zod
, yup
, joi
etc. usually provide a way to define custom error messages. You can use @hishprorg/commodi-distinctio-alias
to translate these messages.
But you need to create the validation schema dynamically, after you have initialized the LL
object ([]i18nObject
](https://github.com/hishprorg/commodi-distinctio-alias/tree/main/packages/runtime#i18nObject)).
You can do that like this by passing the LL
object to a function that returns the validation schema:
import { z } from 'zod'
import type { TranslationFunctions } from './i18n/i18n-types'
export const createLoginSchema = (LL: TranslationFunctions) => z.object({
email: z.string().min(1, LL.validation.emptyField()).email(LL.validation.invalidEmail()),
password: z.string().min(1, LL.validation.emptyField()),
})
By default @hishprorg/commodi-distinctio-alias
at this time does not provide such a functionality. Basically you will need to write a function that splits the translated message and renders a component between the parts. You can define your split characters yourself but you would always need to make sure you add them in any translation since @hishprorg/commodi-distinctio-alias
doesn't provide any typesafety for these characters (yet).
With the strong typesafety features, you'll know if a locale is missing a translation. But in rare cases you might want to use your base translation as a fallback for other locales.
See the next FAQ entry. The same concept can be applied to prefill your translations with the base translation and then just override the parts that are translated.
You'll loose the some sort of typesafety with that approach since you can't know which parts are translated and which are not. Using the base translation as a fallback is not recommended because your UI will contain two different locales which might confuse your users.
Your locale translation files can be any kind of JavaScript object. So you can make object-transformations inside your translation file. The only restriction is: in the end it has to contain a default export with type Translation
. You could do something like this:
create your BaseTranslation
// file 'src/i18n/en/index.ts'
import type { BaseTranslation } from '../i18n-types'
const en: BaseTranslation = {
WELCOME: "Welcome to XYZ",
// ... some other translations
COLOR: "colour"
}
export default en
create your other translation that overrides specific translations
// file 'src/i18n/en-US/index.ts'
import type { Translation } from '../i18n-types'
import en from '../en' // import translations from 'en' locale
const en_US: Translation = {
...en as Translation, // use destructuring to copy all translations from your 'en' locale
COLOR: "color" // override specific translations
}
export default en_US
If you are using nested translations, you should use the provided
extendDictionary
function that usesjust-extend
under the hood.
import { extendDictionary } from '../i18n-utils' import en from '../en' // import translations from 'en' locale const en_US = extendDictionary(en, { labels: { color: "color" // override specific translations } }) export default en_US
The generated types are really strict. It helps you from making unintentional mistakes. If you want to opt-out for certain translations, you can use the any
keyword.
create your BaseTranslation
with a translation containing a parameter
// file 'src/i18n/en/index.ts'
import type { BaseTranslation } from '../i18n-types'
const en: BaseTranslation = {
HELLO: "Hi {name}!",
}
export default en
create another locale without that parameter by disabling the strict type checking with as any
// file 'src/i18n/de/index.ts'
import type { Translation } from '../i18n-types'
const de: Translation = {
HELLO: "Hallo!" as any // we don't want to output the 'name' variable
}
export default de
WARNING! the usage of 'any' can introduce unintentional mistakes in future. It should only be used when really necessary and you know what you are doing.
A better approach would be to create a custom formatter e.g.
create your translation and add a formatter to your variable
// file 'src/i18n/en/index.ts'
import type { BaseTranslation } from '../i18n-types'
const en: BaseTranslation = {
HELLO: "Hi {name|nameFormatter}!",
}
export default en
// file 'src/i18n/de/index.ts'
import type { Translation } from '../i18n-types'
const de: Translation = {
HELLO: "Hallo {name|nameFormatter}!"
}
export default de
create the formatter based on the locale
// file 'src/i18n/formatters.ts'
import type { FormattersInitializer } from '@hishprorg/commodi-distinctio-alias'
import type { Locales, Formatters } from './i18n-types'
import { identity, ignore } from '@hishprorg/commodi-distinctio-alias/formatters'
export const initFormatters: FormattersInitializer<Locales, Formatters> = (locale: Locales) => {
const nameFormatter =
locale === 'de'
// return an empty string for locale 'de'
? ignore // same as: () => ''
// return the unmodified parameter
: identity // same as: (value) => value
const formatters: Formatters = {
nameFormatter: nameFormatter
}
return formatters
}
LocalizedString
and not the type string
itself?With the help of LocalizedString
you could enforce texts in your application to be translated. Lets take an Error message as example:
const showErrorMessage(message: string) => alert(message)
const createUser = (name: string, password: string) => {
if (name.length === 0) {
showErrorMessage(LL.user.create.nameNotProvided())
return
}
if (isStrongPassword(password)) {
showErrorMessage('Password is too weak')
return
}
// ... create user in DB
}
In this example we can pass in any string, so it can also happen that some parts of your application are not translated. To improve your i18n experience a bit we can take advantage of the LocalizedString
type:
import type { LocalizedString } from '@hishprorg/commodi-distinctio-alias'
const showErrorMessage(message: LocalizedString) => alert(message)
const createUser = (name: string, password: string) => {
if (name.length === 0) {
showErrorMessage(LL.user.create.nameNotProvided())
return
}
if (isStrongPassword(password)) {
showErrorMessage('Password is too weak') // => ERROR: Argument of type 'string' is not assignable to parameter of type 'LocalizedString'.
return
}
// ... create user in DB
}
With the type LocalizedString
you can restrict your functions to only translated strings.
Jest
Unfortunately there are some open issues in the Jest
repository regarding modern package export formats so jest
doesn't know where to load files from.
You need to manually tell jest
where these files should be loaded from, by defining moduleNameMapper
inside your jest.config.js
:
// jest.config.js
module.exports = {
moduleNameMapper: {
"@hishprorg/commodi-distinctio-alias/angular": "@hishprorg/commodi-distinctio-alias/angular/index.cjs",
"@hishprorg/commodi-distinctio-alias/react": "@hishprorg/commodi-distinctio-alias/react/index.cjs",
"@hishprorg/commodi-distinctio-alias/solid": "@hishprorg/commodi-distinctio-alias/solid/index.cjs",
"@hishprorg/commodi-distinctio-alias/svelte": "@hishprorg/commodi-distinctio-alias/svelte/index.cjs",
"@hishprorg/commodi-distinctio-alias/vue": "@hishprorg/commodi-distinctio-alias/vue/index.cjs",
"@hishprorg/commodi-distinctio-alias/formatters": "@hishprorg/commodi-distinctio-alias/formatters/index.cjs",
"@hishprorg/commodi-distinctio-alias/detectors": "@hishprorg/commodi-distinctio-alias/detectors/index.cjs",
}
};
here is the original issue with some additional information: #140
Intl
package does not work with locales other than 'en'Node.JS, by default, does not come with the full intl
support. To reduce the size of the node installment it will only include 'en' as locale. You would need to add it yourself. The easiest way is to install the intl
package
> npm install intl
and then add following lines on top of your src/i18n/formatters.ts
file:
const intl = require('intl')
intl.__disableRegExpRestore()
globalThis.Intl.DateTimeFormat = intl.DateTimeFormat
Then you should be able to use formatters from the Intl
namespace with all locales.
Note: this is an older approach to the problem. You should not need this when using Node.js version > 16.
Yarn uses a strange way to install dependencies in a monorepo setup. The issue lays in the "hoisting" of packages (see this issue). Therefore it might be that the @hishprorg/commodi-distinctio-alias
dependencies cannot be found.
Changing the workspace config in package.json will fix the issue:
- "workspaces": [
- "apps/*",
- "packages/*"
- ],
+ "workspaces": {
+ "packages": [
+ "apps/*",
+ "packages/*"
+ ],
+ "nohoist": [
+ "**/@hishprorg/commodi-distinctio-alias",
+ "**/@hishprorg/commodi-distinctio-alias/**"
+ ]
+ },
FAQs
security holding package
We found that @hishprorg/commodi-distinctio-alias demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.