npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@opengenius/react-gettext-parser

v1.9.5

Published

A gettext parser for React. Spits out .pot files!

Downloads

2

Readme

react-gettext-parser

npm version Build Status

A gettext utility that extracts translatable strings from JavaScript, JSX and TypeScript and puts them into a .pot file. It uses the babylon AST parser.

It can be used directly in JavaScript, in gulp, via babel or as a standalone CLI utility to be used in the terminal or from npm scripts.

Features

  • Extracts translatable strings from JavaScript, JSX and TypeScript
  • Maps component names and properties to gettext variables (configurable)
  • Maps function names and arguments to gettext variables (configurable)
  • Merges identical strings found in separate files and concatenates their references
  • Writes .pot content to a specified output file
  • Supports globs
  • Supports flow type
  • Supports string concatenation, e.g. gettext('Foo ' + 'Bar') (useful for wrapping into multiple lines)

Usage

Using the CLI

Providing a config, using a single glob string:

react-gettext-parser --config path/to/config.js --output messages.pot 'src/**/{*.js,*.jsx,*.ts,*.tsx}'

Using an array of glob strings, which is passed to glob-all:

react-gettext-parser --output messages.pot 'src/*.js' '!src/test.js'

The entire help section for ya:

react-gettext-parser <options> glob [, glob, ...]

Options:
  -h, --help       Show help                                          [boolean]
  -o, --output     Path to output .pot file
  -c, --config     Path to a react-gettext-parser config file
  --trim           Trims extracted strings from surrounding whitespace[boolean]
  --trim-lines     Trims each line in extracted strings from surrounding
                   whitespace                                         [boolean]
  --trim-newlines  Trims extracted strings from new-lines             [boolean]

Using the API

// Script somewhere

import { parseGlob } from 'react-gettext-parser';

// Parse a file and put it into a pot file
parseGlob(['src/**/{*.js,*.jsx}'], { output: 'messages.pot' }, () => {
  // Done!
});

// You can also get extracted strings as a list of message objects
import { extractMessagesFromGlob } from 'react-gettext-parser';
const messages = extractMessagesFromGlob(['src/**/{*.js,*.jsx}']);

/*
Results in something like:

[
  {
    msgctxt: "",
    msgid: "Translate me"
    msgstr: [""],
    comments: {
      extracted: ["A comment to translators"],
      reference: [{
        filename:"MyComponent.jsx",
        line:13,
        column:1
      }]
    }
  },
  // And so on...
]
*/

Via babel-plugin-react-gettext-parser

babel --plugins react-gettext-parser src
// .babelrc
{
  "presets": ["es2015", "react"],
  "plugins": [
    ["react-gettext-parser", {
      // Options
    }]
  ]
}

In an npm script

{
  "scripts": {
    "build:pot": "react-gettext-parser --config path/to/config.js --output messages.pot 'src/**/*.js*'"
  }
}

As a gulp task

var reactGettextParser = require('react-gettext-parser').gulp;

gulp.task('build:pot', function() {
  return gulp.src('src/**/*.js*')
    .pipe(reactGettextParser({
      output: 'messages.pot',
      // ...more options
    }))
    .pipe(gulp.dest('translations'));
});

API

Extracting strings

extractMessages(codeStr, [options])

Parses a string with JS(X) or Typescript source code for translatable strings and returns a list of message objects. When use with typescript source code, specify option sourceType as TYPESCRIPT

extractMessagesFromFile(filePath, [options])

Parses a JS(X) or Typescript file for translatable strings and returns a list of message objects.

extractMessagesFromGlob(globStr, [options])

Parses JS(X) or Typescript files matching a glob for translatable strings and returns a list of message objects.

parse(code, [options], [callback])

Parses a string with JS(X) source code for translatable strings and writes a .pot file containing those strings. When use with typescript source code, specify option sourceType as TYPESCRIPT

parseFile(filePath, [options], [callback])

Parses a JS(X) file for translatable strings and writes a .pot file containing those strings.

parseGlob(globStr, [options], [callback])

Parses JS(X) files matching a glob for translatable strings and writes a .pot file containing those strings.

Converting messages to a POT string

toPot(messages, [opts])

Turns an array of messages into a POT string.

  • opts.transformHeaders - A function that takes an object containing default POT headers and returns an object containing transformed POT headers. The default is to return the default headers as is.

Writing POT contents to file

Converts an array of message objects into a POT string.

outputPot(filePath, contents, [callback])

Writes contents to filePath if filePath is truthy, i.e. a string. If filePath is falsy, contents is logged to the console.

Options

output

The destination path for the .pot file. If omitted, the .pot output will be logged to the console.

componentPropsMap

A two-level object of prop-to-gettext mappings.

The defaults are:

{
  GetText: {
    message: 'msgid',
    messagePlural: 'msgid_plural',
    context: 'msgctxt',
    comment: 'comment',
  }
}

The above would make this component...

// MyComponent.jsx
<GetText
  message="One item"
  messagePlural="{{ count }} items"
  count={numItems}
  context="Cart"
  comment="The number of items added to the cart"
/>

...would result in the following translation block:

# The number of items added to the cart
#: MyComponent.jsx:2
msgctxt "Cart"
msgid "One item"
msgid_plural "{{ count }} items"
msgstr[0] ""
msgstr[1] ""
funcArgumentsMap

An object of function names and corresponding arrays of strings that matches arguments against gettext variables.

Defaults:

{
  gettext: ['msgid'],
  dgettext: [null, 'msgid'],
  ngettext: ['msgid', 'msgid_plural'],
  dngettext: [null, 'msgid', 'msgid_plural'],
  pgettext: ['msgctxt', 'msgid'],
  dpgettext: [null, 'msgctxt', 'msgid'],
  npgettext: ['msgctxt', 'msgid', 'msgid_plural'],
  dnpgettext: [null, 'msgid', 'msgid_plural'],
}

This configs means that this...

// Menu.jsx
<Link to="/inboxes">
  { npgettext('Menu', 'Inbox', 'Inboxes') }
</Link>

...would result in the following translation block:

#: Menu.jsx:13
msgctxt "Menu"
msgid "Inbox"
msgid_plural "Inboxes"
msgstr[0] ""
msgstr[1] ""
trim (--trim)

Trims extracted strings from surrounding whitespace.

Default: false

trimLines (--trim-lines)

Trims each line in extracted strings from surrounding whitespace.

Default: false

trimNewlines (--trim-newlines)

Trims extracted strings from new-lines.

Default: false

Developing

Get react-gettext-parser up and running:

npm i && npm run build && npm link

Running the Mocha test suite:

npm test

Dev mode, running build in watch mode:

npm run dev

See also

  • node-gettext - A JavaScript implementation of gettext, a localization framework.
  • gettext-parser - Parsing and compiling gettext translations between .po/.mo files and JSON
  • lioness – Gettext library for React
  • narp - Workflow CLI tool that syncs translations between your app and Transifex

License

ISC