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

Jms Translation Js Extractor Bundle Laravel Package

coffreo/jms-translation-js-extractor-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require coffreo/jms-translation-js-extractor-bundle
    

    For Symfony Flex projects, this auto-enables the bundle. For non-Flex projects, add it to AppKernel.php:

    new Coffreo\JmsTranslationJsExtractorBundle\CoffreoJmsTranslationJsExtractorBundle(),
    
  2. Configure Extractor Add this to config/packages/coffreo_jms_translation_js_extractor.yaml:

    coffreo_jms_translation_js_extractor:
        directories: ['%kernel.project_dir%/assets/js']  # Paths to JS files
        output_dir: '%kernel.project_dir%/translations'  # Output directory for extracted translations
        format: 'json'  # Output format (json, xlf, etc.)
        ignore_patterns: ['node_modules', 'vendor']   # Ignore directories
    
  3. First Use Case Run the extractor via CLI:

    php bin/console coffreo:jms-translation-js-extractor:extract
    

    This scans your JS files (e.g., assets/js/) for translation keys (e.g., __('key')) and generates a translation file (e.g., translations/messages.en.xlf).


Implementation Patterns

Workflow Integration

  1. Development Loop

    • Extract Translations: Run the extractor after adding new JS files or translation strings:
      php bin/console coffreo:jms-translation-js-extractor:extract
      
    • Update JS: Modify your JS files to use extracted keys (e.g., __('welcome.message') instead of hardcoded strings).
    • Commit: Add the generated translation files to version control (or exclude them if using a dynamic system).
  2. CI/CD Pipeline Add the extractor to your build process (e.g., GitHub Actions, GitLab CI):

    # Example GitLab CI snippet
    script:
      - php bin/console coffreo:jms-translation-js-extractor:extract
      - git add translations/
      - git diff --quiet || git commit -m "Update translations"
    
  3. Symfony Translation Workflow

    • Use the extracted files with jms/translation-bundle:
      # config/packages/jms_translation.yaml
      jms_translation:
          configs:
              app:
                  dirs: ['%kernel.project_dir%/translations']
                  output_dir: '%kernel.project_dir%/var/cache/translations'
      
    • Load translations in your JS:
      // assets/js/app.js
      import translations from '../../var/cache/translations/messages.en.json';
      console.log(translations['welcome.message']);
      
  4. Dynamic Key Handling

    • Custom Patterns: Extend the extractor to support custom JS translation patterns (e.g., t('key') or i18n.t('key')):
      coffreo_jms_translation_js_extractor:
          patterns:
              - '__\([\'\"](.*?)[\'\"\)]'
              - 't\([\'\"](.*?)[\'\"\)]'
      
    • Contextual Keys: Use namespaces in JS (e.g., __('user.profile.name')) and map them to Symfony’s translation domains.

Gotchas and Tips

Pitfalls

  1. False Positives

    • The extractor may pick up non-translation strings (e.g., __('some.function()')). Use ignore_patterns to exclude problematic files/directories:
      ignore_patterns: ['tests', 'node_modules', '*.spec.js']
      
    • Tip: Manually review generated translation files for accuracy.
  2. Caching Issues

    • Generated translation files may not update if the extractor isn’t re-run. Clear Symfony’s translation cache after extraction:
      php bin/console cache:clear
      
  3. File Permissions

    • Ensure the output_dir is writable by the web server:
      chmod -R 775 %kernel.project_dir%/translations
      
  4. Symfony Flex Conflicts

    • If using Symfony Flex, ensure the bundle is loaded after JMS\TranslationBundle in bundles.php to avoid autowiring conflicts.

Debugging

  1. Dry Run Mode Use the --dry-run flag to preview changes without writing files:

    php bin/console coffreo:jms-translation-js-extractor:extract --dry-run
    
  2. Verbose Output Enable debug mode for detailed logs:

    php bin/console coffreo:jms-translation-js-extractor:extract --env=dev -v
    
  3. Custom Logger Extend the extractor’s logger to track skipped files or errors:

    // src/Command/ExtractCommand.php (override)
    protected function configure(): void
    {
        $this->setHelp('Extract translations with custom logging.');
        parent::configure();
    }
    

Extension Points

  1. Custom Extractors Implement your own extractor logic by extending Coffreo\JmsTranslationJsExtractorBundle\Extractor\ExtractorInterface:

    namespace App\Extractor;
    
    use Coffreo\JmsTranslationJsExtractorBundle\Extractor\ExtractorInterface;
    
    class CustomExtractor implements ExtractorInterface
    {
        public function extract(string $filePath): array
        {
            // Custom logic to parse JS files
            return ['key' => 'value'];
        }
      }
    

    Register it in services.yaml:

    services:
        App\Extractor\CustomExtractor:
            tags: [coffreo.jms_translation_js_extractor.extractor]
    
  2. Post-Processing Use Symfony’s event system to modify extracted translations. Subscribe to coffreo.jms_translation_js_extractor.post_extract:

    // src/EventListener/TranslationListener.php
    namespace App\EventListener;
    
    use Coffreo\JmsTranslationJsExtractorBundle\Event\PostExtractEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class TranslationListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                'coffreo.jms_translation_js_extractor.post_extract' => 'onPostExtract',
            ];
        }
    
        public function onPostExtract(PostExtractEvent $event): void
        {
            $translations = $event->getTranslations();
            // Modify $translations as needed
            $event->setTranslations($translations);
        }
    }
    
  3. Integration with Webpack Encore If using Encore, configure it to ignore generated translation files:

    // webpack.config.js
    Encore
        // ...
        .configureBabel((config) => {
            config.ignore = [
                /translations\/.*/,
            ];
        });
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver