@tofrankie/gettext-extractor
v0.0.1
Published
A CLI tool to extract gettext messages from JS/TS/JSX/TSX/Vue files
Maintainers
Readme
@tofrankie/gettext-extractor
一个从源代码文件提取 gettext 消息并生成 POT (Portable Object Template) 文件的工具。
✨ 功能特性
- 支持 JS,TS,JSX,TSX,Vue 文件
- 默认支持 gettext 系列函数,也可以自定义函数名映射
gettext(msgid)- 基础翻译ngettext(msgid, msgid_plural, n)- 复数形式pgettext(msgctxt, msgid)- 带上下文npgettext(msgctxt, msgid, msgid_plural, n)- 上下文+复数
📦 安装
pnpm add @tofrankie/gettext-extractor -D🚀 快速开始
命令行使用
# 基础用法
gettext-extract --input src --output locale/messages.pot
# 指定文件类型
gettext-extract --input src --output locale/messages.pot --ext js,ts,jsx,tsx,vue
# 使用配置文件
gettext-extract --config gettext.config.js
# 调试模式
gettext-extract --input src --output locale/messages.pot --debug配置文件
创建 gettext.config.js 放置于项目根目录,还支持 .js, .mjs, .cjs, .ts, .mts, .cts 格式:
import { defineConfig } from '@tofrankie/gettext-extractor'
export default defineConfig({
input: ['src/**/*.{js,ts,jsx,tsx,vue}'],
output: 'locale/messages.pot',
ignore: ['node_modules', 'dist', 'build'],
// 自定义函数配置
functions: {
gettext: ['msgid'],
ngettext: ['msgid', 'msgid_plural'],
pgettext: ['msgctxt', 'msgid'],
npgettext: ['msgctxt', 'msgid', 'msgid_plural'],
},
// POT 文件元数据
potOptions: {
metadata: {
title: 'My Project',
copyright: 'Copyright (C) 2026',
author: 'John Doe',
email: '[email protected]',
},
},
})Node API
import { extract, writePOT } from '@tofrankie/gettext-extractor'
const result = await extract({
input: ['src/**/*.{js,ts,jsx,tsx,vue}'],
ignore: ['node_modules'],
})
console.log(`Extracted ${result.messageCount} messages`)
writePOT('locale/messages.pot', result.content)📖 使用示例
React/JSX
import { gettext, ngettext } from './i18n'
function App() {
return (
<div>
<h1>{gettext('Hello, World!')}</h1>
<p>{ngettext('One item', '%d items', count)}</p>
</div>
)
}Vue SFC
<script setup>
import { gettext } from './i18n'
const message = gettext('Hello from Vue!')
</script>
<template>
<div>
<h1>{{ gettext('Welcome to Vue') }}</h1>
</div>
</template>⚙️ CLI 选项
| 选项 | 描述 | 默认值 |
| ----------------- | --------------------- | ------------------------- |
| -c, --config | 配置文件路径 | 自动查找 |
| -i, --input | 输入文件或目录 | - |
| -o, --output | 输出 POT 文件路径 | messages.pot |
| -e, --ext | 文件扩展名 (逗号分隔) | js,ts,jsx,tsx,vue |
| --ignore | 忽略的模式 | node_modules,dist,build |
| -f, --functions | 函数配置文件 (JSON) | - |
| --debug | 启用调试输出 | false |
🎯 提取规则
支持的模式
// 字符串字面量
gettext('Hello')
// 纯模板字符串
gettext(`Hello`)
// Vue Template 表达式
{{ gettext('Hello') }}
// JSX 表达式
<div>{gettext('Hello')}</div>不支持的模式
// 变量
const msg = 'Hello'
gettext(msg) // ❌
// 函数调用
gettext(getMessage()) // ❌
// 字符串拼接
gettext(`Hello${name}`) // ❌
// 条件表达式
gettext(condition ? 'A' : 'B') // ❌
// 包含表达式的模板字符串 (默认警告,严格模式拒绝)
gettext(`Hello ${name}`) // ⚠️🙏 致谢
📄 License
MIT License © Frankie
