react-edge-translate
v1.2.0
Published
A React translation library using Microsoft Edge translate service with custom translation dictionary support
Downloads
2
Maintainers
Readme
React Edge Translate
A React translation library using Microsoft Edge translate service with custom translation dictionary support. This package provides fast, automatic translation functionality while allowing developers to override poor-quality machine translations with high-quality custom translations.
🚀 Features
- Lightning Fast Translation: Uses Microsoft Edge's public translate service with batch processing
- Instant Page Translation: Automatic translation on language selection, just like translate.js
- Custom Translation Dictionary: Override poor machine translations with high-quality custom translations
- JSON File Management: Easy-to-edit JSON files for managing custom translations
- Priority Translation Logic: Custom translations take priority over API translations
- Developer Tools: Built-in UI for managing, importing, and exporting translation dictionaries
- Translation Analytics: Track usage of custom vs API translations
- React Optimized: Built specifically for React with hooks and components
- Smart Caching: Built-in caching to prevent re-translation and improve performance
- TypeScript: Full TypeScript support with type definitions
- Auto DOM Translation: Automatically translate entire pages without manual triggers
📦 Installation
npm install react-edge-translate
# or
yarn add react-edge-translate🎯 Quick Start
Basic Usage with Custom Translations
import React, { useState } from 'react';
import { useTranslate, TranslationDevTools } from 'react-edge-translate';
function App() {
const [language, setLanguage] = useState('english');
const { translate, isLoading, addCustomTranslation } = useTranslate({
from: 'english',
to: 'chinese_simplified',
customDictionary: { enabled: true }
});
const handleTranslate = async () => {
const result = await translate('Hello World');
console.log(result.translatedText); // Uses custom translation if available
console.log(result.source); // 'custom', 'api', or 'mixed'
};
return (
<div>
<button onClick={handleTranslate} disabled={isLoading}>
Translate
</button>
{/* Developer tools for managing custom translations */}
<TranslationDevTools
from="english"
to="chinese_simplified"
onDictionaryUpdate={(stats) => console.log('Dictionary updated:', stats)}
/>
</div>
);
}Automatic Page Translation with Custom Dictionary
import React, { useState } from 'react';
import { useAutoTranslate, TranslationDevTools } from 'react-edge-translate';
function AutoTranslateApp() {
const [language, setLanguage] = useState('english');
const {
isTranslating,
translationSource,
getTranslationStats,
addCustomTranslation
} = useAutoTranslate({
targetLanguage: language,
sourceLanguage: 'english',
customDictionary: { enabled: true }
});
const stats = getTranslationStats();
return (
<div>
<select value={language} onChange={(e) => setLanguage(e.target.value)}>
<option value="english">English</option>
<option value="chinese_simplified">简体中文</option>
<option value="chinese_traditional">繁體中文</option>
</select>
{isTranslating && <p>Translating...</p>}
<div style={{ marginTop: '20px' }}>
<p>Translation Source: {translationSource}</p>
<p>Custom Translations: {stats.customCount || 0}</p>
<p>API Translations: {stats.apiCount || 0}</p>
</div>
<div id="content">
<h1>Welcome to our website</h1>
<p>This content will be automatically translated!</p>
<p>Custom translations take priority over API translations.</p>
</div>
<TranslationDevTools from="english" to={language} />
</div>
);
}📝 Custom Translation Dictionary System
JSON Dictionary Format
Create translation dictionary files in this format:
{
"metadata": {
"version": "1.0.0",
"lastModified": "2024-06-17T10:30:00.000Z",
"sourceLanguage": "english",
"targetLanguage": "chinese_simplified",
"description": "Custom translations for our website",
"author": "Development Team"
},
"translations": {
"Hello": "你好",
"Welcome": "欢迎",
"Thank you": "谢谢",
"Good morning": "早上好",
"Our company": "我们公司",
"Contact us": "联系我们"
}
}Dictionary File Management
import { useTranslationDictionary } from 'react-edge-translate';
function DictionaryManager() {
const {
dictionary,
addTranslation,
removeTranslation,
exportTranslations,
importTranslations,
getStats
} = useTranslationDictionary({
from: 'english',
to: 'chinese_simplified',
autoLoad: true
});
const handleFileImport = async (event) => {
const file = event.target.files[0];
if (file) {
await importTranslations(file);
}
};
return (
<div>
<h3>Dictionary Management</h3>
<p>Entries: {getStats().entryCount}</p>
<button onClick={() => addTranslation('New text', '新文本')}>
Add Translation
</button>
<button onClick={() => exportTranslations()}>
Export Dictionary
</button>
<input type="file" accept=".json" onChange={handleFileImport} />
</div>
);
}Priority Translation Logic
The translation system follows this priority order:
- Custom Dictionary: Check local JSON translation dictionary first
- API Cache: Check if translation was previously fetched from API
- Microsoft Edge API: Fetch new translation from Microsoft Edge service
- Caching: Cache API results for future use
// Example of translation result with source tracking
const result = await translate(['Hello', 'World', 'Custom text']);
console.log(result);
// {
// success: true,
// translatedText: ['你好', '世界', '自定义文本'],
// source: 'mixed',
// customCount: 1, // 'Custom text' from dictionary
// apiCount: 2 // 'Hello' and 'World' from API
// }🛠️ Developer Tools Component
The TranslationDevTools component provides a UI for managing custom translations:
import { TranslationDevTools } from 'react-edge-translate';
<TranslationDevTools
from="english"
to="chinese_simplified"
className="my-dev-tools"
onDictionaryUpdate={(stats) => {
console.log(`Dictionary now has ${stats.entryCount} entries`);
}}
/>Features:
- Add new custom translations
- Import/export dictionary files
- View translation statistics
- Download example dictionary templates
- Real-time dictionary management
📁 File Structure for Custom Translations
Recommended project structure:
your-project/
├── public/
│ └── translations/
│ ├── english-chinese_simplified.json
│ ├── english-chinese_traditional.json
│ └── example-translations.json
├── src/
│ └── components/
│ └── TranslationManager.tsx
└── package.jsonLoad custom dictionaries:
const { loadCustomDictionary } = useTranslate({
customDictionary: {
enabled: true,
dictionaryPath: './translations/english-chinese_simplified.json'
}
});🔧 Advanced Configuration
Custom Dictionary Configuration
import { edgeTranslator } from 'react-edge-translate';
// Configure the translation system
edgeTranslator.configureDictionary({
enabled: true,
fallbackToAPI: true,
autoReload: true,
cacheTimeout: 300000 // 5 minutes
});File Manager Configuration
import { translationFileManager } from 'react-edge-translate';
translationFileManager.updateConfig({
baseUrl: './custom-translations/',
autoSave: true,
validateOnLoad: true
});📊 Translation Analytics
Track translation usage and performance:
function TranslationAnalytics() {
const { getTranslationStats } = useAutoTranslate({
targetLanguage: 'chinese_simplified'
});
const stats = getTranslationStats();
return (
<div>
<h3>Translation Statistics</h3>
<p>Custom Dictionary Entries: {stats.entryCount}</p>
<p>Custom Translations Used: {stats.customCount || 0}</p>
<p>API Translations Used: {stats.apiCount || 0}</p>
<p>Last Updated: {stats.lastModified}</p>
</div>
);
}📚 API Reference
useTranslate(options?)
Enhanced translation hook with custom dictionary support.
Parameters
options.from: Source language (default: 'english')options.to: Target language (default: 'chinese_simplified')options.cacheResults: Enable caching (default: true)options.customDictionary.enabled: Enable custom dictionary (default: true)options.customDictionary.dictionaryPath: Path to custom dictionary fileoptions.customDictionary.autoReload: Auto-reload dictionary (default: true)
Returns
translate: Function to translate text with custom dictionary priorityisLoading: Loading stateerror: Error message if translation failsaddCustomTranslation: Add custom translation to dictionarygetTranslationStats: Get dictionary statisticsexportDictionary: Export current dictionaryloadCustomDictionary: Load custom dictionary from path
useAutoTranslate(options)
Automatic page translation with custom dictionary support.
Parameters
targetLanguage: Target language for translationsourceLanguage: Source language (default: 'english')customDictionary: Custom dictionary configurationenabled: Enable/disable auto-translation (default: true)
Returns
translatePage: Manually trigger page translationisTranslating: Loading statetranslationSource: Source of last translation ('custom', 'api', 'mixed')addCustomTranslation: Add custom translationgetTranslationStats: Get translation statistics
useTranslationDictionary(options)
Comprehensive dictionary management hook.
Parameters
from: Source languageto: Target languageautoLoad: Auto-load dictionary on mount (default: true)dictionaryPath: Path to dictionary file
Returns
dictionary: Current dictionary objectaddTranslation: Add new translationremoveTranslation: Remove translationimportTranslations: Import from fileexportTranslations: Export to filegetStats: Get dictionary statistics
TranslationDevTools
Developer tools component for dictionary management.
Props
from: Source language (default: 'english')to: Target language (default: 'chinese_simplified')className: Custom CSS classstyle: Custom stylesonDictionaryUpdate: Callback when dictionary is updated
🌍 Supported Languages
english: Englishchinese_simplified: 简体中文 (Simplified Chinese)chinese_traditional: 繁體中文 (Traditional Chinese)
💡 Best Practices
1. Dictionary Organization
{
"translations": {
// UI Elements
"Login": "登录",
"Logout": "登出",
"Submit": "提交",
// Navigation
"Home": "首页",
"About": "关于我们",
"Contact": "联系我们",
// Business Terms
"Our company": "我们公司",
"Premium service": "高级服务"
}
}2. Team Collaboration
- Version Control: Store dictionary files in your repository
- Review Process: Review custom translations before merging
- Consistency: Use consistent terminology across dictionaries
- Documentation: Document translation decisions and context
3. Performance Optimization
// Preload dictionaries for better performance
useEffect(() => {
edgeTranslator.loadCustomDictionary('english', 'chinese_simplified');
}, []);
// Use batch translation for multiple texts
const texts = ['Hello', 'World', 'Welcome'];
const result = await translate(texts); // More efficient than individual calls4. Error Handling
const { translate, error, clearError } = useTranslate({
customDictionary: { enabled: true }
});
if (error) {
console.error('Translation error:', error);
clearError(); // Clear error state
}🔧 Development Workflow
- Setup: Install the package and create initial dictionary files
- Development: Use
TranslationDevToolsto add custom translations - Export: Export dictionaries for review and version control
- Deploy: Include dictionary files in your build process
- Monitor: Track translation usage and update dictionaries as needed
🚀 Migration from v1.1.0
If you're upgrading from v1.1.0, here are the key changes:
// Old way (v1.1.0)
const { translate } = useTranslate();
// New way (v1.2.0) - with custom dictionary support
const { translate, addCustomTranslation } = useTranslate({
customDictionary: { enabled: true }
});
// Add custom translations
addCustomTranslation('Hello', '你好');📄 License
MIT
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
