Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ts-transformer): allow to override user defined message id via overrideIdFn as function #1916

Closed
wants to merge 2 commits into from

Conversation

nodkz
Copy link
Contributor

@nodkz nodkz commented Aug 3, 2020

We can define overrideIdFn as a function that receives msg.id as the first argument.
BUT according to current logic, this function will be never called. And users aren't able to modify already defined id. For example, I want to globally add prefixes to all ids. But cannot do it right now.
This PR fixes this issue.

So current logic will be:

  • overrideIdFn is a string
    • if msg.id is defined leave it unchanged
    • if msg.id is empty then use interpolateName with provided template
  • overrideIdFn is a function
    • pass msg.id to function as first arg. Allow to user decide what to do with id - it may be empty or contain already defined value

@nodkz
Copy link
Contributor Author

nodkz commented Aug 3, 2020

For example, I'm using the following typescript plugin (it adds pkg. prefix to already defined ids OR generate pkg.[contenthash:6] if id is not provided):

// tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "plugins": [
      {
        "transform": "./transformers/react-intl.ts"
      }
    ]
  },
  "exclude": ["node_modules", "**/__tests__", "**/__mocks__"],
  "include": ["src/**/*", "types/types.d.ts"]
}
// ./transformers/react-intl.ts

import { transform, Opts, interpolateName } from '@formatjs/ts-transformer';

export default function intlTransform(opts: Opts) {
  return transform({
    extractFromFormatMessageCall: true,
    overrideIdFn: (
      existedId?: string,
      defaultMessage?: string,
      description?: string,
      filePath?: string
    ) => {
      let id;
      if (existedId) {
        id = existedId;
      } else {
        const content = description ? `${defaultMessage}#${description}` : defaultMessage;
        id = interpolateName({ sourcePath: filePath } as any, '[contenthash:6]', {
          content,
        });
      }
      return `pkg.${id}`;
    },
    onMsgExtracted: (file, msgs) => {
      console.log(msgs);
    },
    ...opts,
  });
}

@longlho
Copy link
Member

longlho commented Aug 4, 2020

you mind adding some tests for the new behavior?

@nodkz
Copy link
Contributor Author

nodkz commented Aug 5, 2020

Closes due #1926

@nodkz nodkz closed this Aug 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants