Auto-generate message IDs for react-intl in tests, allowing you to skip the formatjs babel/swc plugin
npm install react-intl-auto-id-mockAuto-generate message IDs for react-intl in tests, allowing you to skip the formatjs babel/swc plugin for ~35% faster test transforms.
When using react-intl, you typically use a build plugin (like babel-plugin-formatjs or @swc/plugin-formatjs) to auto-generate message IDs from your defaultMessage strings:
``tsx`
// Plugin transforms to:
Without this transform, react-intl throws an error: An 'id' must be provided to format a message.
The problem? These plugins add significant overhead to test transforms:
- @swc/plugin-formatjs is a Wasm module that adds ~35% to transform timebabel-plugin-formatjs
- is even slower
This package mocks react-intl to auto-generate IDs at runtime, letting you skip the plugin entirely in tests.
`bash`
npm install --save-dev react-intl-auto-id-mock
`typescript`
// vitest.setup.ts
import 'react-intl-auto-id-mock/vitest';
Then remove the formatjs plugin from your vitest config:
`typescript
// vitest.config.ts
import react from '@vitejs/plugin-react-swc';
export default defineConfig({
plugins: [
// Remove the formatjs plugin for tests
react(), // instead of react({ plugins: [['@swc/plugin-formatjs', {...}]] })
],
});
`
`typescript`
// jest.setup.ts
import 'react-intl-auto-id-mock/jest';
If you're not sure which framework you're using, the main entry point auto-detects:
`typescript`
import 'react-intl-auto-id-mock';
You can provide a custom ID generator:
`typescript
import { setupReactIntlMock } from 'react-intl-auto-id-mock/vitest';
setupReactIntlMock({
generateId: (defaultMessage, description) => {
return test_${defaultMessage.slice(0, 20)};`
},
});
This package wraps the following react-intl exports to auto-generate IDs:
- useIntl() - The formatMessage function is wrapped
- - Props are patched before renderinginjectIntl()
- - The injected intl.formatMessage is wrapped
In our testing, removing the @swc/plugin-formatjs plugin and using this mock reduced:
- Transform time by ~35%
- Overall test duration by ~20%
- react-intl >= 5.0.0vitest
- >= 1.0.0 or jest` >= 27.0.0
MIT