Giter Club home page Giter Club logo

extract-react-intl-messages's Introduction

extract-react-intl-messages

test tested with jest styled with prettier MIT License All Contributors

This package will generate json or yaml files from a glob. It will generate one file per locale, with the ids of each message defined by the defineMessages function of react-intl. The value of each of these keys will be an empty string, except for your defaultLocale which will be populated with the defaultMessage.

Dependencies

Babel

  • 0.x works with Babel 6

Install

$ npm install --save-dev extract-react-intl-messages

Usage

app/components/App/messages.js

import { defineMessages, useIntl } from 'react-intl'

export default defineMessages({
  hello: {
    id: 'a.hello',
    defaultMessage: 'hello'
  },
  world: {
    id: 'a.world',
    defaultMessage: 'world'
  }
})

export const SubmitButton = () => {
  const intl = useIntl()
  const label = intl.formatMessage({
    id: 'a.submit',
    defaultMessage: 'Submit Button'
  })
  return <button aria-label={label}>{label}</button>
}

Run Script

$ extract-messages -l=en,ja -o app/translations -d en --flat false './app/**/!(*.test).js'

Output

app/translations/en.json

{
  "a": {
    "hello": "hello",
    "world": "world",
    "submit": "Submit Button"
  }
}

app/translations/ja.json

{
  "a": {
    "hello": "",
    "world": "",
    "submit": ""
  }
}

Recommend

Use with babel-plugin-react-intl-auto: i18n for the component age. Auto management react-intl ID.

CLI

$ extract-messages --help

  Extract react-intl messages

  Usage
  $ extract-react-intl-messages <input>
  $ extract-messages <input>

  Options
  -o, --output            Output directory [require: true]
  -l, --locales           locales [require: true]
  -f, --format            json | yaml [default: json]
  -d, --defaultLocale     default locale
  --overwriteDefault      default: false
  --flat                  json [default: true] | yaml [default: false]

  Example
  $ extract-messages --locales=ja,en --output app/translations 'app/**/*.js'
  $ extract-messages -l=ja,en -o i18n 'src/**/*.js'
  $ extract-messages -l=ja,en -o app/translations -f yaml 'app/**/messages.js'

create-react-app user

create .babelrc like this.

{
  "presets": ["react-app"]
}

Run with NODE_ENV=development.

$ NODE_ENV=development extract-messages ...

TypeScript

babel required.

See example/with-typescript

npm install --save-dev @babel/core @babel/preset-typescript @babel/preset-react

babel.config.js

module.exports = function (api) {
  api.cache(true)

  return {
    presets: ['@babel/preset-react', '@babel/preset-typescript']
  }
}

API

extractReactIntlMessages(locales, input, buildDir, [options])

locales

Type: Array<string>

Example: ['en', 'ja']

input

Type: Array<string>

Target files. glob.

buildDir

Type: string

Export directory.

options

defaultLocale

Type: string
Default: en

format

Type: json | yaml
Default: json

Set extension to output.

overwriteDefault

Type: boolean
Default: true

If overwriteDefault is false, it will not overwrite messages in the default locale.

flat

Type: boolean
Default: true

If format is yaml, set to false.

Be careful if false. See this issue.

babel-plugin-react-intl's Options

See https://github.com/formatjs/formatjs/tree/master/packages/babel-plugin-react-intl#options

Contributors

Thanks goes to these wonderful people (emoji key):


akameco

πŸ’» ⚠️ πŸ“– πŸš‡

Hoan Tran

πŸ’» ⚠️

giantpinkwalrus

πŸ’»

enrique-ramirez

πŸ“–

Stefan Gojan

πŸ› πŸ’» ⚠️

Solomon English

πŸ’»

Filip "Filson" Pasternak

πŸ’»

nodaguti

πŸ’» ⚠️

fix-fix

πŸ’»

bradbarrow

πŸ› πŸ’» ⚠️

Gregor MacLennan

πŸ’»

Dmitry Zarva

πŸ’»

Michael Pan

πŸ’‘

Tom Erik StΓΈwer

πŸ’»

Bart Lens

πŸ’»

Truong Hoang Dung

πŸ’‘

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT Β© akameco

extract-react-intl-messages's People

Contributors

akameco avatar allcontributors[bot] avatar bradbarrow avatar dependabot[bot] avatar enrique-ramirez avatar fix-fix avatar giantpinkwalrus avatar greenkeeper[bot] avatar hoantran-it avatar hoschi avatar lensbart avatar nodaguti avatar panpanc avatar remcohaszing avatar revskill10 avatar solomon23 avatar testower avatar toshitanian avatar zarv1k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

extract-react-intl-messages's Issues

It is not clear how to run this Scritpt for noobs...

Hi,

I do not understand how to run this script, yes I am a noob... but

Run Script
$ extract-messages -l=en,ja -o app/translations -d en --flat false 'app/**/!(*.test).js'

is not really helpfull... Do I need to run this command in the shell where I ran the npm install...?
-this is what I get:

$ extract-messages -l=en,ja -o app/translations -d en --flat false 'app/**/!(*.test).js' bash: extract-messages: command not found

So I need to run it somewhere else, or do something else before running it?

Please explain what is the difference between the packages: extract-react-intl/extract-react-intl-messages

Thank you

How to avoid duplicate keys

If I have defineMessages in different files with the same ids, extract-react-intl-messages simply overwrites them. How to make it throw an error

Not working with babel-plugin-react-intl-auto?

  • version: 0.10.0
  • node version: 10.4.1
  • npm version: 6.2.0

Using babel-plugin-react-intl-auto 1.1.0, I always encounter an error:
[React Intl] Message Descriptors require an id and defaultMessage.

How can I fix this?

babel-plugin-react-intl has been initialised using an options object that does not match the API schema

  • version:
  • node version:
  • npm (or yarn) version: 1.19.0

Do you want to request a feature or report a bug?:
Bug

What is the current behavior?:

./node_modules/extract-react-intl-messages/cli.js -o src/i18n/messages -l=en,fr,de -d en --flat false 'src/**/*.js'
ValidationError: [BABEL] /path/to/foo.js: Invalid options object. babel-plugin-react-intl has been initialised using an options object that does not match the API schema.
 - options has an unknown property 'f'. These properties are valid:
   object { moduleSourceName?, enforceDefaultMessage?, enforceDescriptions?, extractSourceLocation?, messagesDir?, overrideIdFn?, removeDefaultMessage?, extractFromFormatMessageCall?, additionalComponentNames
? } (While processing: "base$0$0")
    at Object.validate [as default] (/path/to/node_modules/babel-plugin-react-intl/node_modules/schema-utils/dist/validate.js:50:11)

What is the expected behavior?:

Suggested solution:

Versions after 2.2.1 deletes translation files content

Tested with two versions:

  • node 10.x and 12.13.0:
  • npm 6.11.13 and 6.12.0:

The v2.3.0 - v2.3.3 all versions delete translation files content.

Instead of en fills with the extracted messages and other languages are with key and "" value pairs, all translation files content filled only "{}"

Simple test: as in the example shows.

Package json:

"dependencies": {
    "@giantmachines/redux-websocket": "^1.1.3",
    "babel-plugin-react-intl": "^4.1.21",
    "classnames": "^2.2.6",
    "connected-react-router": "^6.5.2",
    "history": "^4.9.0",
    "react": "^16.8.6",
    "react-css-modules": "^4.7.11",
    "react-dates": "^20.3.0",
    "react-dom": "^16.8.6",
    "react-intl": "^2.9.0",
    "react-intl-translations-manager": "^5.0.3",
    "react-redux": "^7.1.0",
    "react-router-dom": "^5.0.1",
    "react-router-redux": "^4.0.8",
    "react-scripts": "3.0.1",
    "react-toastify": "^5.3.2",
    "recharts": "^1.7.1",
    "redux": "^4.0.4",
    "redux-form": "^8.2.5",
    "redux-logger": "^3.0.6",
    "redux-orm": "^0.13.3",
    "redux-thunk": "^2.3.0",
    "ws": "^7.1.2"
  },

  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/preset-react": "^7.0.0",
    "@types/react-intl": "^3.0.0",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "css-loader": "^3.1.0",
    "extract-react-intl-messages": "^2.3.3",
    "file-loader": "^4.2.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.12.0",
    "path": "^0.12.7",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "svg-inline-loader": "^0.8.0",
    "svg-inline-react": "^3.1.0",
    "uglifyjs-webpack-plugin": "^2.1.3",
    "webpack": "^4.37.0",
    "webpack-cli": "^3.3.6",
    "webpack-dev-server": "^3.7.2",
    "webpack-merge": "^4.2.1"
  }

Turn off values overwritting

Hi

By default, when I want to extract translations (e.x. to en.json file) and this file is already present, this plugin overrides previously present translations. Is there a way to turn off overwritting?

Example
I have a file messages.js with

export default defineMessages({
    foo: 'bar'
})

Then, i extract this to en.json:

{
    "foo": "bar"
}

But, my translator changes this line

{
   "foo": "anotherBar"
}

Then, when i run extraction again i would expect this line to stay the same, but instead i recieve

{
    "foo": "bar"
}

Generated files are empty

Hi

Your project seems matching all my need, thanks for the work :)

When i run this command, the generated files are empty:

NODE_ENV=development ./node_modules/.bin/extract-messages --locales=en -d en --output app/translations 'src/**/*.+(ts|tsx)'

Content of the generated file:

cat app/translations/en.json 
{}

My project uses create-react-app ([email protected]) with typescript.

Here is the code of one of my components:

import React from 'react';
import { FormattedMessage } from 'react-intl';

const Loading = () => {
  return (
    <div>
      <FormattedMessage id="loading.text" />
    </div>
  );
};

export default Loading;

Does the parser read the data from <FormattedMessage />?

  • version:
  • node version: v12.16.1
  • npm version: 6.14.0
  • extract-react-intl-messages: 3.0.0

Regards

Feature: allow multiple default locales, for defaultMessage

New Feature

What is the current behavior?:
When running the script, it will insert the default message for the default locale only, and an empty string for other locales.
If i don't update immediately my locale files, react-intl fails and displays the id

What is the expected behavior?:
The purpose of the default message is to be a fallback.
I would want to export it by default, instead of an empty string

Suggested solution:
Either allow an array of default locales as a param, or a specific option that allows to extract the default message to every locale file

Whitespace at end of strings is stripped

extract-react-intl-messages - 0.8.2

Do you want to request a feature or report a bug?:
bug

What is the current behavior?:
Whitespace at the end of a string is removed

What is the expected behavior?:
Extracted text should match the input text

Suggested solution:
Don't strip whitespace

defineMessage (singular) definitions not extracted

  • version: 4.1.1
  • node version: v14.15.1
  • npm (or yarn) version: yarn 1.22.15

Do you want to request a feature or report a bug?:
bug or help wanted

What is the current behavior?:
defineMessage (singular) not extracted but defineMessages works ok.

What is the expected behavior?:
extract defineMessage and defineMessages definitions

Suggested solution:
Not sure if i am doing something wrong but I can not get extracted messages when I define them using singular defineMessage method. Everything works fine with defineMessages.

Tool does not export messages defined with intl.formatMessage

  • version:
  • node version: v10.16.3
  • npm (or yarn) version: 6.9.0

Do you want to request a feature or report a bug?:
I want to report 'bug'? Not sure if its a bug, maybe just delete from README.md or i missed something
What is the current behavior?:
After i used the command, messages defined with intl.formatMessage are not exported
NODE_ENV=development extract-messages -l=en,ja -o src/translations -d en --flat false "./src/**/*.tsx"
What is the expected behavior?:
Like in the README.md it should export the messages.
Suggested solution:
If you dont have this feature, remove it from README.md or suggest a flag on how to use it.

What to do with locale files

Not an issue, just a question: when exporting locale files, and using extract-messages with react-intl-auto I end up with a plain object with ids and empty strings.
How do you suggest one should go on from this?
The way I thought I could work on locale was to obtain an it.json file, for instance, with english translations, and translate line by line just editing the file. However the ID is not clear enough, and I have to go back and forth from then en.json file to check what I should translate..I'm surely doing something wrong in the process...any suggestions?
Thanks!
Andrea

Output to terminal

Do you want to request a feature or report a bug?:
Feature

What is the current behavior?:
It's required that we specify output file

Suggested solution:
It would be helpful to be able to output the parsed translation file to the console in absence of -o attribute.

My use case is that I want to create one file with localization strings per directory in my project. This would means tens of files. I'd then want to upload these files to our localization tool, which means tens of requests. However, I could upload all these resource(files) all that in one go, if I were able to merge all the files into one.

So as you can see, I'd be first generating tens of files, then reading them and merging their contents. What would be helpful is to be able to just run extract-react-intl-messages in loop to get all of them in one go.

Empty translation files if project uses babel.config.js instead of .babelrc

  • version: 4.1.1
  • node version: 12.11.1
  • yarn version: 1.22.4

I have used this tool about a year ago (#35 ), in a react-native project, And it worked fine, now, with the same setup, on a newly generated project I'm only getting empty files.

package.json

{
"scripts": {
    ...
    "i18n:extract": "extract-messages -l=en,sv -o src/Locales -d en --flat true 'src/**/!(*.test).ts'",
  },
  "dependencies": {
    ...
    "@formatjs/intl-relativetimeformat": "^4.5.9",
    "intl": "^1.2.5",
    "intl-pluralrules": "^1.1.1",
    "react": "16.13.1",
    "react-intl": "^4.3.1",
    "react-native": "0.62.1",
    ...
  },
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.0",
    "@babel/preset-typescript": "^7.9.0",
    "@babel/runtime": "^7.8.4",
    "babel-plugin-react-intl": "^7.1.0",
    "extract-react-intl-messages": "^4.1.1",
    "metro-react-native-babel-preset": "^0.59.0",
    "react-intl-translations-manager": "^5.0.3",
    ...
  },
}

babel.config.js

module.exports = {
  presets: [
    '@babel/preset-typescript',
    'module:metro-react-native-babel-preset',
  ],
};

src/Screens/Profile/Profile.messages.ts

import {defineMessages} from 'react-intl';

export const messages = defineMessages({
  ...
  fieldPersonalNumber: {
    id: 'profile.field.personalNumber',
    defaultMessage: 'Personal number',
    description: 'Field label for the personal number field',
  },
});

What is the current behavior?:
If you generate a new react-native project, the babel config is handled in an babel.config.js file. The result is empty translation files

src/Locales/en.json

{}

What is the expected behavior?:
That the default translation file contains the keys and default message.
src/Locales/en.json

{
  "profile.field.personalNumber": "Personal number"
}

Workaround:
Duplicate your babel.config.js to a .babelrc in your project (React-native requires babel.config.js).

Suggested solution:
Add support for babel.config.js files.
add a notice in the readme that this tool requires @babel/preset-typescript as a preset in your babel config.

--enforceDefaultMessage false does not work in cli

  • version:
  • node version: 10.13.0
  • npm (or yarn) version: 1.12.3

Do you want to request a feature or report a bug?:
bug
What is the current behavior?:
enforceDefaultMessage option does not work in cli because there is no type case of 'false' string to boolean false
What is the expected behavior?:

Suggested solution:
cast babel-plugin-react-intl boolean type options in cli

Does not work with Typescript?

Hi,

I understand this can be quite challenging to support but that would be useful to be able to use this on typescript projects. In my case it's a Gatsby site with Typescript plugin, so there's not even a .babelrc config. Not sure how this can be done, just reporting that this script is failing on such a file:


import React, { ReactNode } from 'react';
import classnames from 'classnames';

const CartItem = ({
  label,
  price,
  children,
}: {
  label: string;
  price: number;
  children: ReactNode;
}) => (
  <article className="cart-item">
    <p className="cart-item__title">
      <b>{label}</b>
      <span className="cart-item__price">{price}€</span>
    </p>
    <p className="cart-item__detail">{children}</p>
  </article>
);

export default CartItem;

Crashes for empty directory

  • version:
  • node v8.7.0:
  • npm 5.4.2:

Do you want to request a feature or report a bug?:
Bug

What is the current behavior?:
When trying to parse multiple directories, if one of them is empty the script crashes with Error: File not found (./path/to/empty/directory/**/!(*.test).js)

What is the expected behavior?:
Script does not crash, and either creates an empty file for empty directory (since no strings were found), or gives a warning that nothing was found.

Suggested solution:
As above.

Error: File not found :(

Hi, thanks for the effort πŸ‘

  • version: ^0.8.2
  • node version: v8.9.4
  • npm (or yarn) version: 1.5.1 (Yarn)

Do you want to request a feature or report a bug?:
Bug

What is the current behavior?:
Throw Error (Error: File not found ('src/components/app.jsx')
command : extract-messages -l=ar -o src/locales 'src/components/app.jsx'
the file is there, trying extract-messages -l=ar -o src/locales 'src/**/*.jsx' throws File not found ('src/**/*.jsx') same thing for JS files

What is the expected behavior?:
Extract messages

Suggested solution:
I have no idea

P.S. Im using create-react-app

How to use extract-react-intl-messages in react-native project ?

  • version: 2.3.3
  • node version: 10.17.0
  • npm (or yarn) version: npm 6.11.3

Do you want to request a feature or report a bug?:
bug

What is the current behavior?:
When use with react-native project, end with this error :

ValidationError: [BABEL]: Invalid options object. babel-plugin-react-intl has been initialised using an options object that does not match the API schema.

  • options has an unknown property 'f'. These properties are valid:
    object { moduleSourceName?, enforceDefaultMessage?, enforceDescriptions?, extractSourceLocation?, messagesDir?, overrideIdFn?, removeDefaultMessage?, extractFromFormatMessageCall?, additionalComponentNames? } (While processing: "base$0$0")

babel.config.js is like this:
module.exports = { presets: ['module:metro-react-native-babel-preset'], };

What is the expected behavior?:
extract messages work well with react-native init apps

Suggested solution:

No output

Running the extract-messages CLI command, I get empty objects in each of the expected dictionary files.

After digging a bit through the source code, this is the culprit:

presets.unshift({
   plugins: [
     [
       babelPluginReactIntl,
       Object.entries(pluginOptions).reduce((acc, [key, value]) => {
         if (babelPluginReactIntlOptions.includes(key)) {
           return { ...acc, [key]: value }
         }
         return acc
       }, {})
     ]
   ]
 })

Commenting out these lines gets the script in working order.

It seems that the Babel plugin that’s added to the presets array, fails to pass the metadata property along that contains the messages.

All my dependencies are up-to-date.

Hope this helps!

Restore the `module-name` option

Do you want to request a feature or report a bug?:
Feature

What is the current/expected behavior?:
What was the reason that the module-name option was removed in 2.0.0? I'd like to upgrade to version 2, but my use case requires that functionality.

Suggested solution:
Looking at the commit that removed it, it doesn't seem like the functionality would be too hard to restore, but I'm not sue if there was an underlying reason that necessitated its deletion.

Add option to specify prefix for unused messages

Can you add option to specify prefix for unused messages? So their keys look different.

{
    " __[UNUSED]__ screens.Login.FacebookButton.title: "Login with Facebook"
}

This code does this

const difference = require('lodash/difference')
const keys = require('lodash/keys')

...

return extractReactIntl(locales, pattern, {
    defaultLocale,
  }).then(newLocaleMaps => {
    return Promise.all(
      locales.map(locale => {
        // If the default locale, overwrite the origin file



        const unusedMessagesIds = difference(
          keys(oldLocaleMaps[locale]),
          keys(newLocaleMaps[locale])
        )

        unusedMessagesIds.forEach(messageId => {
          if (!/^\s\s__\[UNUSED\]__\s\s/.test(messageId)) {
            oldLocaleMaps[locale][`  __[UNUSED]__  ${messageId}`] =
              oldLocaleMaps[locale][messageId]
            delete oldLocaleMaps[locale][messageId]
          }
        })



Library is thinking that there might be an HTML tag in defaultMessage

  • version: 4.1.1
  • node version: 12.14.1
  • npm version: 6.14.5

I presume that the library is thinking that there might be an HTML tag in this defaultMessage. How can I fix this?

SyntaxError: Expected "#", "'", "\n", "{", argumentElement, double apostrophes, end of input, or tagElement but "<" found.
  38 |  test: {
  39 |          id: 'test.test',
> 40 |          defaultMessage: '< 10'
     |                          ^^^^^^
  41 |  }
  42 | });
  43 | 
    at File.buildCodeFrameError (D:\Dev\unispektras-service-app-fe\node_modules\@babel\core\lib\transformation\file\file.js:248:12)
    at NodePath.buildCodeFrameError (D:\Dev\unispektras-service-app-fe\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\index.js:144:21)
    at getICUMessageValue (D:\Dev\unispektras-service-app-fe\node_modules\babel-plugin-react-intl\dist\index.js:66:27)
    at evaluateMessageDescriptor (D:\Dev\unispektras-service-app-fe\node_modules\babel-plugin-react-intl\dist\index.js:113:26)
    at processMessageObject (D:\Dev\unispektras-service-app-fe\node_modules\babel-plugin-react-intl\dist\index.js:388:38)
    at Array.forEach (<anonymous>)
    at PluginPass.CallExpression (D:\Dev\unispektras-service-app-fe\node_modules\babel-plugin-react-intl\dist\index.js:415:38)
    at newFn (D:\Dev\unispektras-service-app-fe\node_modules\@babel\core\node_modules\@babel\traverse\lib\visitors.js:179:21)
    at NodePath._call (D:\Dev\unispektras-service-app-fe\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:55:20)
    at NodePath.call (D:\Dev\unispektras-service-app-fe\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:42:17)

Doesn't work with babel.config - only looks for .babelrc

  • version: 2.2.1
  • node version: 12.40
  • npm (or yarn) version: yarn 1.17.3

Do you want to request a feature or report a bug?:
A bug

What is the current behavior?:
In a monorepo structure tried to run extract-messages in a package folder, raises Add @babel/plugin-proposal-export-default-from (https://git.io/vb4yH) to the 'plugins' section of your Babel config to enable transformation

What is the expected behavior?:
That it works as expected

Suggested solution:
It seems to me that the script doesn't load babel.config.js babel configurations, and just expects a .babelrc in a parent directory. Adding the plugin as suggested by the aforementioned error in the babel.config has no effects indeed

Extracting messages with defineMessages exported from custom module does not work.

  • version: 0.10.0
  • node version: 10.4.1
  • npm version: 6.1.0

Do you want to request a feature or report a bug?:
Bug or support

What is the current behavior?:
In my project I managed JS module to handle internationalization. It is based on react-intl but extends it with some custom components, predefined configs, extra features etc.
Because of that, I wanted to avoid necessity of imports from react-intl AND my own module, so decided to export required react-intl elements via my modules' index.js file.

Everything works great, but I figured out that when I run npm script to extract messages with extract-react-intl-messages, it does not work any more. It creates files, but there are no messages. Something like on screenshots below.

image

image

If I import defineMessages directly from react-intl it works as expected.

What is the expected behavior?:
I expect it to work exactly the same with both variants. Not sure why it's not working correctly. defineMessages is not any special kind of function. In fact, it does nothing except returning passed values.

Invalid string length error if used with babel-plugin-react-intl-auto

Hi! I am not able to make extract-react-intl-messages working with babel-plugin-react-intl-auto.

My .babelrc has following content:

{
  "presets": [
    [ "env", { "modules": false, "loose": true } ],
    "react"
  ],
  "plugins": [
    "transform-object-rest-spread",
    [ "transform-class-properties", { "loose": true } ],
    [ "react-intl-auto", { "filebase": true } ]
  ]
}

I execute messages extraction via node ./node_modules/extract-react-intl-messages/cli.js -l=en -o translations 'src/**/*.js'

If any of my .js files has message without id example: <FormattedMessage defaultMessage="Try again" /> then extraction ends up with:

RangeError: Invalid string length
    at JSON.stringify (<anonymous>)
    at then.str (/Users/matejprokop/dev/react-components/node_modules/write-json-file/index.js:40:22)
    at <anonymous>

If I add missing id to the message definition. Then extraction script works as expected and produce translations/en.json

  • node version: v8.9.2
  • npm (or yarn) version: 5.5.1

Probably, I overlooked some important detail. Let me know if you need more info. Thank you!

Support variable

  • version: 0.14.0
  • node version: 11.9.0
  • yarn version: 1.13.0

report a bug

The script is not working using variables:

const messages = { hello: 'hello world' }

export default defineMessages(messages)

What is the current behavior?:

[React Intl] defineMessages() must be called with an object expression with values that are React Intl Message Descriptors, also defined as object expressions.

Prettify output

Hello!

Thanks for your good work.

It would be nice if the project would check the presence of Prettier and format the generated output accordingly.

Thanks for your consideration!

Question : Support of moduleSourceName to accept detection from a different module ?

Hi, sorry I didn't know where else to put this.

I'm actually looking remove the default <span> from previous version of react-intl and in this regard I have created a passthrough component which wrap in a so nothing get broken with legacy css.

But this way the extraction of messages can not work and I though It would be great if this lib could support a given list of path to watch for extraction instead of being limited to react-intl

Getting an error for using FormattedHTMLMessage

  • version:
  • node version: 12
  • yarn version: 1.22
  • react-intl version: 2.9.0

Do you want to request a feature or report a bug?:
bug.
(would be a feature if this functionality is missing altogether)

What is the current behavior?:
When using FormattedHTMLMessage to parse the following string -
Sample message string : Hello <span class='bold'>'{name}'</span>

I'm getting an 'unexpected token' error.

yarn run v1.22.4
$ extract-messages -l=messages -o dist -d en './src/components/**/!(*.test).js'
SyntaxError: [React Intl] Message failed to parse. See: https://formatjs.io/docs/icu-syntax
SyntaxError: Expected "#", "'", "\n", "{", argumentElement, double apostrophes, end of input, or tagElement but "<" found. (This is an error on an internal node. Probably an internal error.)
    at File.buildCodeFrameError (/project/node_modules/@babel/core/lib/transformation/file/file.js:248:12)
    at NodePath.buildCodeFrameError (/project/node_modules/@babel/traverse/lib/path/index.js:144:21)
    at getICUMessageValue (/project/node_modules/extract-react-intl-messages/node_modules/babel-plugin-react-intl/dist/index.js:66:27)
    at evaluateMessageDescriptor (/project/node_modules/extract-react-intl-messages/node_modules/babel-plugin-react-intl/dist/index.js:113:26)
    at processMessageObject (/project/node_modules/extract-react-intl-messages/node_modules/babel-plugin-react-intl/dist/index.js:388:38)
    at Array.forEach (<anonymous>)
    at PluginPass.CallExpression (/project/node_modules/extract-react-intl-messages/node_modules/babel-plugin-react-intl/dist/index.js:415:38)
    at newFn (/project/node_modules/@babel/traverse/lib/visitors.js:179:21)
    at NodePath._call (/project/node_modules/@babel/traverse/lib/path/context.js:55:20)
    at NodePath.call (/project/node_modules/@babel/traverse/lib/path/context.js:42:17)
error Command failed with exit code 1.

What is the expected behavior?:
Expecting this to be extracted like the other messages.

Suggested solution:

Append new translations to extracted json

Hi!
First, thank you for your great work with this plugin!

However, I extracted messages to json file (worked as expected), then I introduced new messages and tried to extract messages again.

Expected:

  • new messages are appended to json file, keeping already present content untouched

Observed:

  • content is untouched (as expected) but new messages are not appended to json document (not as expected)

Steps to reproduce:

  • extract messages (default language en, other languages: de)
  • add new messages
  • add any translations to de.json file
  • extract messages again
  • check content of both en.json and de.json

Extract-messages pattern

Hi there, I am using Windows machine with Node v12. Working on CRA app with Typescript. Can you suggest how to properly use pattern when executing extract-messages cli command. I Always have erros like 'File not found' or '.js unexpected'.

CWD: C:\Users\Zvone\projects\forum-eu\publication
/n/n >>>> '.src\pages\common\ConfirmationEmailPage.tsx' [] function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}

if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}

return new Glob(pattern, options, cb)
}
Error: File not found ('.src\pages\common\ConfirmationEmailPage.tsx')
at Object.exports.default (C:\Users\Zvone\projects\forum-eu\publication\node_modules\extract-react-intl-messages\dist\extract-react-intl\index.js:113:15)

Produce flat json structure

  • version: 0.10.0
  • node version: 10.4.1
  • npm (or yarn) version: 6.1.0

Do you want to request a feature or report a bug?:
Not sure πŸ˜‰

What is the current behavior?:
The extraction process is performed correctly. I use it to produce json files. The 'flat' flag is set to true by default, but the result is nested structure. Am I missing the real responsibility of that flag or it's not working well (if the latter, I report a bug).

What is the expected behavior?:
React-Intl's IntlProvider expects single level object in messages props, so it is needed functionality to generate one. I know it is possible to set up additional step to the script and flatten those files, but if extract-react-intl-messages can (or already should) do it automatically, why not to use it?

extractReactIntl named export is overwritten

  • version: 2.3.3
  • node version: 10.16.0
  • npm (or yarn) version: yarn 1.19.1

Do you want to request a feature or report a bug?:
Report a bug

What is the current behavior?:

const { extractReactIntl } = require('extract-react-intl-messages');
// extractReactIntl is undefined

What is the expected behavior?:
The symbol is exported from the module, so I want to be able to import it.

Suggested solution:

In index.ts, at line 67, you do

export const extractReactIntl = _extractReactIntl

But at line 138 you write this

module.exports = extractMessage

For CommonJS, line 67 is transpiled to exports.extractReactIntl = _extractReactIntl, so at line 138 you overwrite completely exports.

Easiest fix, since you want to be able to use require without .default, would be simply to assign extractReactIntl as a property of extractMessage:

extractMessage.extractReactIntl = _extractReactIntl

export default extractMessage

// For CommonJS default export support
module.exports = extractMessage
module.exports.default = extractMessage

This way you don't change your API (but on the other hand you always get extractReactIntl when you import default, which is not problematic given that this module is not meant to be used in a tree-shaking context).

[Support] Is it not compatible with babel v6 any more?

Is this tool incompatible with babel6 because of changes introduced in 0.12 version?
When I was testing module-name feature on my branch everything worked fine. Now, I found that extracting messages to files is not possible 😞

  • version: 0.13
    image

Support for extracting message and IDs from intl.formatMessage function

  • version: 1.0.1
  • node version: v10.16.0
  • npm (or yarn) version: 6.9.0

**Do you want to request a feature or report a bug?:

Feature

**What is the current behavior?:

Do not support extracting message text and ID from intl.formatMessage function call

**What is the expected behavior?:

When extracting messages and IDs , Extract them from intl.formatMessage function calls as well

**Suggested solution:

Accept the extractFromFormatMessageCall argument in extract-messages command and pass it to babel-plugin-react-intl through extract-react-intl

So that, When extractFromFormatMessageCall is passed as an argument, It will generate the message text and IDs passed to intl.formatMessage calls.

extractFromFormatMessageCall: Opt-in to extract from intl.formatMessage call with the same restrictions, e.g: has to be called with object literal such as intl.formatMessage({ id: 'foo', defaultMessage: 'bar', description: 'baz'})

Empty default string [React Intl] Message Descriptors require an `id` and `defaultMessage`

  • version: 1.0.1
  • node version: 10.1
  • npm (or yarn) version: 1.15.2

**Do you want to request a feature or report a bug?:Bug

What is the current behavior?:

export default defineMessages({
  toolsTitle: '',
});
const extractReactIntlMessages = require('extract-react-intl-messages');

const locales = ['en', 'en-GB'];
const pattern = 'components/**/*.ts';
const buildDir = 'static/i18n/locales';
const defaultLocale = 'en';

extractReactIntlMessages(locales, pattern, buildDir, { defaultLocale }).then(
  () => {
    console.log('finish');
  },
);

[React Intl] Message Descriptors require an idanddefaultMessage``
What is the expected behavior?:

Suggested solution:
Should allow default empty strings?

.js was unexpected at this time

  • version: 0.14/1.0.0 (explicitly tried both version, I guess they are same)
  • Windows 10
  • Babel 7
  • node version: 10.13
  • npm (or yarn) version: YARN 1.13/ NPM 6.41 (tried both)
    Do you want to request a feature or report a bug?:
    Bug
    What is the current behavior?:
    I'm getting error when running this command:

"scripts": {
        "extract-messages": "extract-messages -l=en,ja -o ./translations -d en --flat false 'app/**/!(*.test).js'"
    },

Error message: .js was unexpected at this time

What is the expected behavior?:

Should run without errors and produce localization files

Suggested solution:

Support __dirname as a part of the build directory

  • version:
  • node version:
  • npm (or yarn) version:

Do you want to request a feature or report a bug?:
Feature

What is the current behavior?:
Currently, there is a static buildDir (e.g. app/translations) which produces translations in a single file (one per locale).

What is the expected behavior?:
We could support <dirname> in the buildDir, so we could extract the messages to a JSON file inside the component folder.

For instance, if we have an app/components/Button/index.ts file, then its messages could be extracted to aop/components/Button/translations/en-US.json if we set the buildDir to <dirname>/translations.

Suggested solution:
Simply replacing <dirname> with __dirname.

Issue with delimiter.

  • version: 0.10.0
  • node version: 8.10.0
  • yarn version: 1.7.0

Do you want to request a feature or report a bug?:
Bug
What is the current behavior?:
I tried using --delimiter flag but it doesn't work.
What is the expected behavior?:
It should work.

Example not working scripts:
NODE_ENV=development extract-messages -l=en --flat --delimiter / -o src/translations 'src/**/!(*.test).js'
NODE_ENV=development extract-messages -l=en --flat --delimiter '/' -o src/translations 'src/**/!(*.test).js'

The output json is the same, eg.

"containers.A.welcome": "Welcome!"

instead of

"containers/A/welcome": "Welcome!"

Json key not generated for fields defined by defineMessages from gatsby-plugin-intl

Thanks for this great plugin! I run into problems with gatsby and TS, any help or pointer would be greatly appreciated.

  • version: 4.1.1
  • node version: 12.4
  • npm (or yarn) version: yarn 1.22.4

Do you want to request a feature or report a bug?: bug

What is the current behavior?:
I import defineMessages from gatsby-plugin-intl, not from react-intl.
When running

extract-messages -l=en,fr -o src/intl -d en --flat false './src/pages/**/!(*.test).tsx'

on a page containing:

import { useIntl, FormattedMessage, defineMessages } from "gatsby-plugin-intl";

  const intl = useIntl();
  const messages = defineMessages({
    description: {
      id: "about.description",
      defaultMessage: "this description isn't picked up",
      values: {
        newline: <br />,
      },
    },
  });

  return (
        <h1 className="title">
          {intl.formatMessage({
            id: "about.title",
            defaultMessage: "About me",
          })}
        </h1>
        <FormattedMessage {...messages.description} />
  )

it detects and generates only the title, not the description message:

// en.js
{
  "about": {
    "title": "About me"
  }
}

What is the expected behavior?:
I would expect:

// en.js
{
  "about": {
    "title": "About me",
    "description": "this description isn't picked up",
  }
}

TypeError: fn is not a function

  • version: 0.9.1
  • node version: v8.11.2
  • npm (or yarn) version: 5.6.0

Do you want to request a feature or report a bug?:

Bug

What is the current behavior?:

When invoking extract-messages -o translations -l de src/**/*.js the output is

TypeError: fn is not a function
    at list.map.x (/Users/ms/p/vaamo/vam-frontend/node_modules/extract-react-intl/index.js:25:42)
    at Array.map (<anonymous>)
    at /Users/ms/p/vaamo/vam-frontend/node_modules/extract-react-intl/index.js:25:8
    at extractFromFile (/Users/ms/p/vaamo/vam-frontend/node_modules/extract-react-intl/index.js:74:16)
    at Array.map (<anonymous>)
    at pify.then.files (/Users/ms/p/vaamo/vam-frontend/node_modules/extract-react-intl/index.js:93:32)
    at <anonymous>

and the file translations/de.json contains only {}.

What is the expected behavior?:

No error output and a correctly filled translations/de.json.

Suggested solution:

I am still trying to minimise the project this happens on but already wanted to open the issue in case somebody knows immediatly what might trigger the bug.

Regression with the cli script after updating Meow

After updating the meow library there seems to be a regression, leading to none of the aliases working when calling the cli script.

extract-messages -o ./translations -l=ja,en --d en 'test/**/*.js'

Expected outcome:
en.json and ja.json appearing in translations folder

Actual outcome:
cli errors out ERROR: Required output

Fix #7

Add option to provide custom babel configuration.

Hi,

Currently 'extract-react-intl-messages' requires babel.config.js or .babelrc in the project root directory. When we have a custom configuration in another file it doesn't work. Could you please add option to pass custom babel configuration as an argument to the extractReactIntlMessages function?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.