Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Js Translation Extractor Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require coffreo/js-translation-extractor
    

    Add the service provider to config/app.php:

    Coffreo\JsTranslationExtractor\JsTranslationExtractorServiceProvider::class,
    
  2. Basic Usage Extract translations from a JS file:

    use Coffreo\JsTranslationExtractor\Extractor;
    
    $extractor = new Extractor();
    $translations = $extractor->extractFromFile('path/to/your/script.js');
    
  3. First Use Case

    • Scan your frontend JS files for hardcoded strings (e.g., "Welcome", "Submit").
    • Generate a .json or .php translation file for Laravel’s resources/lang/.

Implementation Patterns

Workflows

  1. Integration with Laravel Mix/Webpack

    • Run extraction during 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');
          });
      
    • Create a custom Mix plugin (laravel-mix-extend) to trigger extraction after build.
  2. Automated CI/CD Pipeline

    • Add extraction as a pre-commit hook or GitHub Action:
      # .github/workflows/extract-translations.yml
      - name: Extract JS Translations
        run: php artisan js:extract
      
  3. Dynamic Extraction

    • Use the CLI command for one-off extractions:
      php artisan js:extract path/to/directory --output=lang/en.json
      

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. False Positives

    • The default regex may match non-translation strings (e.g., "2023-01-01").
    • Fix: Whitelist known keys or adjust the pattern:
      $extractor->setPattern('/\$t\(\'(.*?)\'\)|__\(\'(.*?)\'\)/');
      
  2. Dynamic Keys

    • Keys like "user.{{ id }}" won’t extract cleanly.
    • Fix: Pre-process JS files or use a two-pass extraction.
  3. Performance

    • Recursively scanning large directories (e.g., node_modules) is slow.
    • Fix: Exclude directories:
      $extractor->setExcludes(['node_modules', 'vendor']);
      
  4. Encoding Issues

    • Non-ASCII characters (e.g., "Café") may break extraction.
    • Fix: Ensure files are UTF-8 encoded and use mb_* functions if needed.

Debugging

  • Log Extracted Strings
    $extractor->setLogger(function($string) {
        Log::debug('Extracted: ' . $string);
    });
    
  • Validate Output Compare extracted keys against your translation files for consistency.

Extension Points

  1. Custom Patterns Override the default regex for frameworks like i18next:

    $extractor->setPattern('/i18next\.t\(\'(.*?)\'\)/');
    
  2. Post-Processing Normalize keys (e.g., trim whitespace, lowercase):

    $extractor->setKeyNormalizer(function($key) {
        return strtolower(trim($key));
    });
    
  3. Output Formats Extend the Extractor class to support .po or .yaml:

    class PoExtractor extends Extractor {
        public function toPo(): string { ... }
    }
    
  4. 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);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky