@coolon/i18n-resource-generator
v4.1.0
Published
Generates typescript classes from yml resource bundles using the icu message format
Keywords
Readme
i18n-resource-generator
Generates ts classes from yml resource bundles using the icu message format
Installation
npm i @coolon/i18n-resource-generatorTypescript Cofniguration
Add the following to your tsconfig.json
"resolveJsonModule": true,
"esModuleInterop": true,Create a directory for your messages
Create a directory for your message files: e.g. apps/my-app/src/i18n
Add a i18n.config.json file to it with the following:
{
"srcDirs": ["src/app"], // locations to scan for i18n.yml files.
"outDir": "src/app", // where to generate the I18n class and locale files
"class": "I18n", // optional, but can be a different name. Useful for libraries
"customTypeImports": { // optional, but you'll typically want these with AUP
"Alert": "import {Alert} from '@coolon/angular-ui-powerups'",
"Confirm": "import {Confirm} from '@coolon/angular-ui-powerups'",
"NavItem": "import {NavItem} from '@coolon/angular-ui-powerups'",
"CommandFace": "import {CommandFace} from '@coolon/angular-ui-powerups'",
"ColumnTextProperties": "import {ColumnTextProperties} from '@coolon/angular-ui-powerups'"
}
}Relative paths are resolved relative to the config file.
Message files
Add one or more yaml files under the paths specified in the config file: e.g.
In my-properties.i18n.uml
plain_messages:
say_hello: "Hello {name}"
enums:
place_navigation(Enum):
home:
title: "Home"
icon_name: "home"
devices:
title: "Devices"
icon_name: "device_icon"
custom_types:
alerts(Alert[]):
save_failed:
content:
- "The save operation failed"
ok: "Bugger"
another_message:
content:
- "Content can also have"
- "Multiple lines"
ok: "Sweet"
confimrations(Confirm[]):
discard_changes:
content:
- "Discard the changes to {name}"
ok: "Yes"
cancel: "Cancel"
destructive: truee Namespaces
The generator will create namespaces based on the file names and directory structure.
<src dir>/ # Namespace and code usage
i18n.yml # illegal, files in the src root must have an explicit name like my-properties.i18n.yml
my-properties.i18n.yml # Uses file name, i.e. I18n.myProperties.<yaml properties>
components/
i18n.yml # I18n.components.<yaml properties> (plain i18n files use directory as namesapce)
components.i18n.yml # I18n.components.<yaml properties> (same name as directory uses directory namespace)
special.i18n.yml # I18n.components.special.<yaml properties>Running the generator
$ i18n-resource-generator --help
Usage: i18n-resource-generator [options] <configFile>
Options:
-V, --version output the version number
-h, --help output usage informationAdd a run script to your package.json In this case we're placing our source files in apps/my-app/ and our generated output in apps/my-app/src/app.
{
"scripts": {
"i18n": "i18n-resource-generator apps/my-app/i18n.config.json"
}
} Then run the script.
npm run i18nThen your output dir with have:
<out dir>/
i18n.ts
locals/
en.json // generated from your yaml files.. don't edit.Create additional translations inside the locales directory.
Then use I18n.ts in your project:
import {I18n} from "./i18n.ts";
// the "en" locale will be used by default.
const message = I18n.myMessages.plainMessages.sayHello('World!!!');
interactionContext.alert(I18n.customTypes.alerts.saveFailed())
// Register a new locale.
import spanishBundle from "./locales/es.json";
I18n.registerBundle("es", spanishBundle);
// and use it
I18n.setLocale('es');
// get installed locales
I18n.getAvailableLocales().forEach(locale => console.log(locale));There is also a special message bundle called message-keys that can be loaded which simply uses the
messages keys as the text. This bundle doesn't appear in the I18n.getAvailableLocales() result.
// and use it
I18n.setLocale('message-keys');Custom types
A yaml key annotated with a registered type name generates an object of that type instead of a bare namespace. Register the type's import in your config:
{
"customTypeImports": {
"CommandFace": "import {CommandFace} from '@my-org/ui'"
}
}(Type) makes that one key an instance; (Type[]) makes each of its children one:
saveButton(CommandFace):
text: Save
style: raised
commands(CommandFace[]):
save:
text: Save
cancel:
text: CancelNesting
A custom type can hold other custom types, which is how you build a bundle of faces or alerts:
wording(Wording[]):
defaults:
label: "Manage devices"
manageDevices(CommandFace):
text: Manage devices
style: strokedThe inner annotation is required. The generator never reads your TypeScript, so manageDevices
is only known to be a CommandFace because the key says so. A plain object inside a custom type is
an error, naming the key it gave up on.
Arguments stop at the nearest custom type
An ICU argument is bound by the closest enclosing node that emits a complete typed object — not by
the outermost entry. So a {count} on one member leaves its siblings alone:
wording(Wording[]):
defaults:
label: "Manage devices" # no arguments
addConfirm(CommandFace):
text: "{count, plural, one{Add 1} other{Add #}}" # binds count itself// `defaults` is still a value, despite the {count} inside it
export const defaults: Wording = {
label(): string { ... },
addConfirm(count: number): CommandFace { ... }
};Only arguments on the entry's own leaves widen its signature, and a nested member's arguments never join it:
greeting:
label: "Hello {who}"
addConfirm(CommandFace):
text: "{count, plural, one{Add 1} other{Add #}}"export function greeting(who: string): Wording { ... } // `who` only — never (who, count)A leaf that binds its own arguments
Arguments stop at the nearest node that emits a complete typed object — which means a scalar member has no boundary of its own, and its argument still pools into the entry. Annotate the leaf with its return type to opt it out:
wording(Wording[]):
defaults:
label: "Manage devices"
prompt(string): "{count, plural, one{1 selected} other{# selected}}"export const defaults: Wording = {
label(): string { ... },
prompt(count: number): string { ... } // its own signature; `defaults` stays a value
};Without the annotation the entry becomes defaults(count: number), so a caller would have to know a
count before it could read any member of the set — including ones that have nothing to do with it.
Pooling remains the default because it is what a framework-consumed contract needs: Confirm.title()
and CommandFace.text() are called with no arguments, so those members must stay zero-argument and
take their values from an enclosing accessor. Annotate one of those and you break its caller. The
annotation must also agree with the consuming interface (prompt?: (count: number) => string); the
compiler enforces that, since the emitted object is checked or cast against its declared type.
One shape worth avoiding: pooling a leaf whose interface does declare a parameter emits a zero-argument member, which stays assignable to the declared type — so the call site is made to pass an argument that is silently ignored. Annotate it.
Scalars only. A string array member is not supported: in practice every one is framework-consumed
(Alert.content(): string[]), and (string[]) would collide with the (Type[]) map-of-entries
syntax.
Named arguments
"argStyle": "named" makes every generated accessor take one object rather than positional
parameters:
{ "argStyle": "named" }I18n.messages.greet({ name: 'World' });Prefer it for new projects. Positional order follows yaml key order, so reordering keys — or adding a member that carries an argument above an existing one — silently reorders the signature; where the reordered parameters share a type, every call site keeps compiling and renders the values in the wrong slots.
A custom type's interface is specific to the style, since a member carrying arguments is generated as
(args: {...}) => T under named and (a, b) => T under positional. Switching a project means
updating its custom interfaces too. The compiler will tell you which, provided strictFunctionTypes
is on — function-typed properties are only checked contravariantly under that flag.
Checking custom types instead of casting them
By default a generated object is cast to its declared type (const x = {...} as T), so a member the
interface doesn't declare, or a required one left out, passes silently. "checkCustomTypes": true
emits const x: T = {...} instead, which is checked:
{ "checkCustomTypes": true }It is opt-in because the cast is load-bearing for an interface that narrows a text member beyond what
can be generated from a yaml string — type?: () => SomeUnion can only ever be emitted as
type(): string. Turn it on per project once that project's types line up. Enabling it across an
existing codebase is a good way to find yaml that never did anything: a destructive: true under a
(CommandFace[]) key (valid on Confirm, not on CommandFace) or an (Alert) entry missing its
required ok.
Parse failures
A file that fails to parse aborts the run: nothing is written and the exit code is non-zero. Earlier versions logged the error and carried on, which still produced output and exited 0 — everything in the offending file from the bad key onwards was silently dropped, and because the emitted object was cast to its declared type the truncated result type-checked and built cleanly.
