Comprehensive configuration options for babel-plugin-formatjs, allowing customization of message extraction, ID generation, and output processing behavior.
Configure the plugin in your Babel configuration.
/**
* Main plugin function that creates the Babel plugin
* @param api - Babel API object (automatically provided)
* @param options - Plugin configuration options
* @param dirname - Directory name (automatically provided)
* @returns Babel plugin object
*/
declare const plugin: (
api: object,
options: Options | null | undefined,
dirname: string
) => PluginObj<PluginPass>;Usage Examples:
// babel.config.js - Basic setup
module.exports = {
plugins: ["babel-plugin-formatjs"]
};
// babel.config.js - With options
module.exports = {
plugins: [
["babel-plugin-formatjs", {
idInterpolationPattern: "[sha512:contenthash:base64:6]",
removeDefaultMessage: true,
onMsgExtracted: (filename, messages) => {
console.log(`Extracted ${messages.length} messages from ${filename}`);
}
}]
]
};Control how message IDs are generated and handled.
interface IDGenerationOptions {
/** Custom function to override ID generation */
overrideIdFn?: (
id?: string,
defaultMessage?: string,
description?: string,
filePath?: string
) => string;
/** Pattern for automatic ID interpolation when no ID is provided */
idInterpolationPattern?: string;
}Usage Examples:
// Custom ID generation function
{
overrideIdFn: (id, defaultMessage, description, filePath) => {
// Generate custom ID based on file path and message
const fileName = filePath.split('/').pop().replace('.js', '');
return `${fileName}.${defaultMessage.toLowerCase().replace(/\s+/g, '_')}`;
}
}
// Using interpolation pattern
{
idInterpolationPattern: "[contenthash:base64:8]"
}
// File-based ID pattern
{
idInterpolationPattern: "[path][name].[hash:6]"
}Configure callbacks to handle extracted messages and metadata.
interface ExtractionCallbacks {
/** Called when messages are extracted from a file */
onMsgExtracted?: (filePath: string, msgs: MessageDescriptor[]) => void;
/** Called when metadata is extracted from pragma comments */
onMetaExtracted?: (filePath: string, meta: Record<string, string>) => void;
}Usage Examples:
{
onMsgExtracted: (filePath, messages) => {
// Save messages to JSON file
const fs = require('fs');
const output = JSON.stringify(messages, null, 2);
fs.writeFileSync(`./messages/${path.basename(filePath)}.json`, output);
},
onMetaExtracted: (filePath, meta) => {
// Log metadata for debugging
console.log(`Meta from ${filePath}:`, meta);
}
}Extend the plugin to recognize additional component and function names.
interface ComponentFunctionOptions {
/** Additional JSX component names to process (beyond FormattedMessage) */
additionalComponentNames?: string[];
/** Additional function names to process (beyond formatMessage, $t, $formatMessage) */
additionalFunctionNames?: string[];
}Usage Examples:
{
// Process custom components
additionalComponentNames: ['CustomMessage', 'TranslatedText', 'I18nString'],
// Process custom functions
additionalFunctionNames: ['translate', '__', 'i18n', 'getMessage']
}Control how the transformed output is processed and optimized.
interface OutputProcessingOptions {
/** Remove defaultMessage properties to reduce bundle size */
removeDefaultMessage?: boolean;
/** Pre-parse messages into AST format */
ast?: boolean;
/** Preserve whitespace in message strings */
preserveWhitespace?: boolean;
}Usage Examples:
{
// Remove default messages for production builds
removeDefaultMessage: process.env.NODE_ENV === 'production',
// Parse messages into AST for runtime efficiency
ast: true,
// Keep original whitespace formatting
preserveWhitespace: true
}Configure extraction of source location and metadata from pragma comments.
interface MetadataOptions {
/** Extract source location information (line, column, file) */
extractSourceLocation?: boolean;
/** Pragma comment prefix for metadata extraction */
pragma?: string;
}Usage Examples:
{
// Include source locations in extracted messages
extractSourceLocation: true,
// Custom pragma for metadata
pragma: '@react-intl'
}Pragma Usage in Source Code:
// @react-intl namespace:user-profile locale:en-US
import { defineMessages } from 'react-intl';
const messages = defineMessages({
greeting: {
defaultMessage: 'Hello there!'
}
});interface Options {
/** Custom function to override ID generation */
overrideIdFn?: (
id?: string,
defaultMessage?: string,
description?: string,
filePath?: string
) => string;
/** Called when messages are extracted from a file */
onMsgExtracted?: (filePath: string, msgs: MessageDescriptor[]) => void;
/** Called when metadata is extracted from pragma comments */
onMetaExtracted?: (filePath: string, meta: Record<string, string>) => void;
/** Pattern for automatic ID interpolation when no ID is provided */
idInterpolationPattern?: string;
/** Remove defaultMessage properties to reduce bundle size */
removeDefaultMessage?: boolean;
/** Additional JSX component names to process */
additionalComponentNames?: string[];
/** Additional function names to process */
additionalFunctionNames?: string[];
/** Pragma comment prefix for metadata extraction */
pragma?: string;
/** Extract source location information */
extractSourceLocation?: boolean;
/** Pre-parse messages into AST format */
ast?: boolean;
/** Preserve whitespace in message strings */
preserveWhitespace?: boolean;
}The plugin uses these default values when options are not specified:
idInterpolationPattern: "[sha512:contenthash:base64:6]"removeDefaultMessage: falseadditionalComponentNames: [] (defaults include FormattedMessage)additionalFunctionNames: [] (defaults include formatMessage, $t, $formatMessage)extractSourceLocation: falseast: falsepreserveWhitespace: false{
extractSourceLocation: true,
onMsgExtracted: (filename, messages) => {
console.log(`Found ${messages.length} messages in ${filename}`);
}
}{
removeDefaultMessage: true,
ast: true,
idInterpolationPattern: "[sha512:contenthash:base64:8]"
}{
additionalComponentNames: ['MyMessage', 'TransText'],
additionalFunctionNames: ['translate', '__'],
overrideIdFn: (id, defaultMessage, description, filePath) => {
return `custom.${defaultMessage.toLowerCase().replace(/\s+/g, '.')}`;
},
onMsgExtracted: (filename, messages) => {
// Custom message processing
messages.forEach(msg => processMessage(msg, filename));
}
}