compile-module.d.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { StringStructure } from './compiler';
  2. import MessageFormat, { MessageFunction } from './messageformat';
  3. export { MessageFunction, StringStructure };
  4. /**
  5. * The type of the generated ES module, once executed
  6. *
  7. * @public
  8. * @remarks
  9. * Use with `Shape` extending the {@link StringStructure} that was used as
  10. * the module source.
  11. */
  12. export type MessageModule<Shape, ReturnType extends 'string' | 'values' = 'string'> = Shape extends string ? MessageFunction<ReturnType> : {
  13. [P in keyof Shape]: MessageModule<Shape[P], ReturnType>;
  14. };
  15. /**
  16. * Compile a collection of messages into an ES module
  17. *
  18. * @public
  19. * @remarks
  20. * Available as the default export of `'@messageformat/core/compile-module'`, to
  21. * allow for its exclusion from browser builds.
  22. *
  23. * With `messages` as a hierarchical structure of ICU MessageFormat strings,
  24. * the output of `compileModule()` will be the source code of an ES module with
  25. * a default export matching the input structure, with each string replaced by
  26. * its corresponding JS function. If the input includes anything other than
  27. * simple variable replacements, the output ES module will have a dependency on
  28. * `'@messageformat/runtime'`.
  29. *
  30. * If the `messageformat` instance has been initialized with support for more
  31. * than one locale, using a key that matches the locale's identifier at any
  32. * depth of a `messages` object will set its child elements to use that locale.
  33. * To customize this behaviour, see {@link MessageFormatOptions.localeCodeFromKey}.
  34. *
  35. * @example
  36. * ```
  37. * import { writeFileSync } from 'fs'
  38. * import MessageFormat from '@messageformat/core'
  39. * import compileModule from '@messageformat/core/compile-module'
  40. *
  41. * const mf = new MessageFormat('en')
  42. * const msgSet = {
  43. * a: 'A {TYPE} example.',
  44. * b: 'This has {COUNT, plural, one{one member} other{# members}}.',
  45. * c: 'We have {P, number, percent} code coverage.'
  46. * }
  47. * const msgModule = compileModule(mf, msgSet)
  48. * writeFileSync('messages.js', msgModule)
  49. *
  50. * ...
  51. *
  52. * import messages from './messages'
  53. *
  54. * messages.a({ TYPE: 'more complex' }) // 'A more complex example.'
  55. * messages.b({ COUNT: 3 }) // 'This has 3 members.'
  56. * ```
  57. *
  58. * @param messageformat - A {@link MessageFormat} instance
  59. * @param messages - A hierarchical structure of ICU MessageFormat strings
  60. */
  61. export default function compileModule(messageformat: MessageFormat<'string' | 'values'>, messages: StringStructure): string;