Skip to content

[macros] Configurable default context value generation for macrosΒ #2357

@mogelbrod

Description

@mogelbrod

Problem Description

My organization is currently evaluating switching from i18next to another i18n solution, and lingui is currently the most promising candidate.

After converting most of our existing i18next usage to lingui macros using a custom codemod we ended up with many reused translation strings across multiple files. We'd like to avoid string reuse, which can be accomplished by specifying context. It's unfortunately not immediately obvious to a developer when they'd be expected to provide context, as it's to my knowledge only possible to see if a translation is reused by manually checking the po file after running the extract command. This implies that the only safe approach is to manually specify context everywhere, which would essentially nullify the DX improvement which lingui provides by using key-less translations.

Also, specifying context for <Trans> macros is simple enough but I'm not aware of any way to do so for the t macro. Is it possible to specify context for t macros without having to switch to i18n._()?

Proposed Solution

If it was possible to automatically generate default context values for the t/<Trans> macros the above limitations could be avoided. Two possible solution I can think of:

  1. Pass a (filePath: string) => string | undefined function in the lingui config that returns the default context for a given file path. If a JS function isn't possible I'd suggest a regex approach like ^.*/src/(?<context>.+?)(\.[jt]sx?)?$ so that leading/trailing noise can be omitted.
  2. Allow custom pragmas/directives to control lingui macro conversion on a per-file basis, example:
    /* @lingui context=myContext */
    
    This could apply until the next @lingui comment in the same file.
    This would be more repetitive and easier to forger than (1) since devs would need to remember to add it, although it can be forced via eslint rule or similar.

Alternatives Considered

  • Manually specifying context everywhere, which would essentially nullify the DX improvement which lingui provides by using key-less translations.

Additional Context

Looking forward to hearing your thoughts!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions