coffreo/js-translation-extractor
Extracts Laravel translation strings used in JavaScript by scanning your frontend source. Helps keep locale files in sync with JS usage and reduces missing-key issues in mixed Blade/Vue/React apps.
Installation
composer require coffreo/js-translation-extractor
Add the service provider to config/app.php:
Coffreo\JsTranslationExtractor\JsTranslationExtractorServiceProvider::class,
Basic Usage Extract translations from a JS file:
use Coffreo\JsTranslationExtractor\Extractor;
$extractor = new Extractor();
$translations = $extractor->extractFromFile('path/to/your/script.js');
First Use Case
"Welcome", "Submit")..json or .php translation file for Laravel’s resources/lang/.Integration with Laravel Mix/Webpack
post-build:
// webpack.mix.js
mix.postCss('resources/css/app.css', 'public/css', [])
.js('resources/js/app.js', 'public/js')
.then(() => {
require('laravel-mix-extend').run('js-translations');
});
laravel-mix-extend) to trigger extraction after build.Automated CI/CD Pipeline
# .github/workflows/extract-translations.yml
- name: Extract JS Translations
run: php artisan js:extract
Dynamic Extraction
php artisan js:extract path/to/directory --output=lang/en.json
Laravel Localization Merge extracted translations with existing language files:
$existing = require base_path('resources/lang/en/messages.php');
$new = $extractor->extractFromFile('script.js');
file_put_contents(
base_path('resources/lang/en/messages.php'),
'<?php return ' . json_encode(array_merge($existing, $new)) . ';'
);
Vue/React Projects
Target template strings (e.g., {{ 'Hello' }} in Vue) by customizing the regex pattern:
$extractor->setPattern('/{{[\s]*[\'\"](.*?)[\'\"][\s]*}}/');
Testing Mock translations in tests:
$translations = $extractor->extractFromString('$t("test.key")');
$this->assertArrayHasKey('test.key', $translations);
False Positives
"2023-01-01").$extractor->setPattern('/\$t\(\'(.*?)\'\)|__\(\'(.*?)\'\)/');
Dynamic Keys
"user.{{ id }}" won’t extract cleanly.Performance
node_modules) is slow.$extractor->setExcludes(['node_modules', 'vendor']);
Encoding Issues
"Café") may break extraction.mb_* functions if needed.$extractor->setLogger(function($string) {
Log::debug('Extracted: ' . $string);
});
Custom Patterns Override the default regex for frameworks like i18next:
$extractor->setPattern('/i18next\.t\(\'(.*?)\'\)/');
Post-Processing Normalize keys (e.g., trim whitespace, lowercase):
$extractor->setKeyNormalizer(function($key) {
return strtolower(trim($key));
});
Output Formats
Extend the Extractor class to support .po or .yaml:
class PoExtractor extends Extractor {
public function toPo(): string { ... }
}
Parallel Processing
Use Laravel’s parallel helper for large codebases:
$files = glob('resources/js/**/*.js');
$results = collect($files)->parallel()->map(function($file) use ($extractor) {
return $extractor->extractFromFile($file);
});
How can I help you explore Laravel packages today?