@testgorilla/tgo-icu-transpiler
v1.0.2
Published
Transloco ICU MessageFormat transpiler that works under a CSP without 'unsafe-eval'
Maintainers
Keywords
Readme
@testgorilla/tgo-icu-transpiler
Transloco transpiler for ICU MessageFormat ({n, plural, ...}, {x, select, ...}) that interprets messages with
intl-messageformat instead of compiling them to JavaScript.
It replaces @jsverse/transloco-messageformat, whose @messageformat/core compiles every message with new Function
and so needs 'unsafe-eval' in the Content Security Policy.
Installation
npm install @testgorilla/tgo-icu-transpiler
npm uninstall @jsverse/transloco-messageformat @messageformat/coreRequires @jsverse/transloco 7 or 8 and Angular 16 or later.
Usage
Replace provideTranslocoMessageformat() with provideIcuTranspiler() wherever Transloco is provided, including test
modules:
import { provideTransloco } from '@jsverse/transloco';
import { provideIcuTranspiler } from '@testgorilla/tgo-icu-transpiler';
export const appConfig: ApplicationConfig = {
providers: [provideTransloco({ config, loader }), provideIcuTranspiler()],
};Escape free text passed as a {{ }} param, since {{ }} interpolation runs before ICU parsing:
import { escapeIcuParam } from '@testgorilla/tgo-icu-transpiler';
this.transloco.translate('JOB.TITLE', { title: escapeIcuParam(job.title) });Jest in the consuming app must transform the ESM-only dependencies, e.g.
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$|@formatjs|intl-messageformat)'].
Differences from @jsverse/transloco-messageformat
- A missing plain
{x}argument renders empty instead ofundefined/null. - Plural categories the locale lacks (e.g.
onein Japanese) are ignored instead of throwing. - A missing or unknown select/plural value falls back to
otherinstead of throwing. escapeIcuParamoutput followed by an apostrophe ({{name}}'s) renders without a stray'. Otherwise an apostrophe only quotes{,}or#when a later apostrophe closes it, as before (l'{company}rendersl'Acme).- Known gap: escaped input containing braces inside a quoted HTML attribute (
<a title='{{name}}'>) throwsMALFORMED_ARGUMENT, because the attribute'and the escape'merge into''. The old transpiler rendered garbled text instead. Use double quotes for such attributes (title="{{name}}").
API
| Export | Description |
| ------------------------ | ------------------------------------------------------------------- |
| provideIcuTranspiler() | Environment providers registering IcuTranspiler as the transpiler |
| IcuTranspiler | The TRANSLOCO_TRANSPILER implementation |
| escapeIcuParam(value) | Escapes {, } and ' so a param value renders literally |
Checking against @jsverse/transloco-messageformat
scripts/messageformat-equivalence.spec.ts renders an app's translation files with both transpilers and reports the
differences. Run it after changing how messages are parsed; the header has the command.
