@better-intl/compiler
v0.11.1
Published
AST extractor and Babel/SWC transform for better-intl
Readme
@better-intl/compiler
AST extractor and Babel/SWC transform for better-intl.
Extracts translatable text from JSX at build time and transforms it into optimized t() calls — or inlines translations for zero-runtime cost.
Install
npm install @better-intl/compilerUsage
Extract messages from source
import { extract } from "@better-intl/compiler";
const messages = extract(
`export function Hero() {
return <h1>Hello world</h1>;
}`,
{ filePath: "src/Hero.tsx" }
);
// [{ id: "0rr2b7c", defaultMessage: "Hello world", filePath: "src/Hero.tsx", ... }]Transform JSX
import { transform } from "@better-intl/compiler";
// Runtime mode — replaces text with t() calls
const result = transform(source, {
filePath: "src/Hero.tsx",
mode: "auto",
});
// Zero-runtime mode — inlines translated text
const result = transform(source, {
filePath: "src/Hero.tsx",
locale: "pt-BR",
messages: { "0rr2b7c": "Olá mundo" },
});Catalog utilities
import {
generateDefaultCatalog,
mergeCatalog,
findMissingKeys,
findDeadKeys,
} from "@better-intl/compiler";
// Generate default locale catalog from extracted messages
const catalog = generateDefaultCatalog(messages);
// Merge new messages into existing catalog (preserves translations)
const { messages, added, removed } = mergeCatalog(existing, extracted);
// Find missing translations
const missing = findMissingKeys(enCatalog, ptBrCatalog);
// Find unused keys
const dead = findDeadKeys(catalog, extracted);Babel plugin
// babel.config.js
module.exports = {
plugins: [
["@better-intl/compiler/babel", {
locale: "pt-BR",
messages: require("./locales/pt-BR.json"),
}],
],
};Webpack loader
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.[jt]sx$/,
use: ["@better-intl/compiler/webpack-loader"],
},
],
},
};API
| Export | Description |
|--------|-------------|
| extract(source, options) | Extract translatable messages from JSX |
| transform(source, options) | Transform JSX text into t() calls or inline translations |
| generateDefaultCatalog(messages) | Generate catalog for default locale |
| mergeCatalog(existing, extracted) | Merge new messages preserving existing translations |
| findMissingKeys(default, target) | Find keys missing in target locale |
| findDeadKeys(catalog, extracted) | Find unused keys in catalog |
License
MIT
