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

Asset Mapper Laravel Package

symfony/asset-mapper

Symfony AssetMapper exposes asset directories, copies them to a public folder with digested/versioned filenames, and can generate an importmap so you can use modern JavaScript modules without a build step.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package via Composer:

    composer require symfony/asset-mapper
    

    For Laravel 10+, use the Symfony AssetMapperBundle (if available) or manually integrate the component.

  2. Configure config/asset_mapper.php (create if missing):

    return [
        'source_dirs' => [
            resource_path('assets'), // Your source assets (e.g., `resources/assets`)
        ],
        'public_dir' => public_path('build'), // Output directory (e.g., `public/build`)
        'version_strategy' => 'hash', // Use 'hash' for cache-busting filenames
        'import_map' => [
            'entrypoints' => [
                'app' => [
                    'main.js', // Entry point for importmap
                ],
            ],
        ],
    ];
    
  3. Run the mapper via Artisan:

    php artisan asset-map:dump
    

    This generates versioned assets (e.g., main.[hash].js) in public/build and an importmap.json.

  4. Use in Blade/Twig:

    <!-- Option 1: Directly reference versioned assets -->
    <script type="module" src="{{ asset('build/main.[hash].js') }}"></script>
    
    <!-- Option 2: Use importmap (modern JS) -->
    <script type="importmap">
      {
        "imports": {
          "react": "https://esm.sh/react@18",
          "lodash": "/build/lodash.[hash].js"
        }
      }
    </script>
    
  5. First Use Case:

    • Replace manual ?v=1.2 versioning with auto-generated hashes.
    • Enable ES modules for a new React component without Webpack.

Where to Look First

  • Symfony Docs: Official guide for configuration and CLI commands.
  • config/asset_mapper.php: Customize source directories, output paths, and versioning strategies.
  • Artisan Commands:
    • asset-map:dump: Generate versioned assets and importmap.
    • asset-map:watch: Auto-rebuild on file changes (dev only).
  • public/build/importmap.json: Auto-generated importmap for ES modules.

First Workflow

  1. Add a new JS file (e.g., resources/assets/js/app.js).
  2. Run php artisan asset-map:dump.
  3. Reference the versioned file in Blade:
    <script type="module" src="{{ asset('build/app.[hash].js') }}"></script>
    
  4. Verify cache-busting: Open DevTools → Network tab → Check filename includes a hash.

Implementation Patterns

1. Asset Versioning Workflow

  • Pattern: Use version_strategy: 'hash' for cache-busting filenames (e.g., styles.[hash].css).
  • Integration:
    • Configure in config/asset_mapper.php:
      'version_strategy' => 'hash', // or 'timestamp' for dev
      
    • Laravel Mix/Vite users: Replace mix-manifest.json with the auto-generated importmap.json for ES modules.
    • Blade Helper: Create a custom helper to generate versioned asset URLs:
      // app/Helpers/AssetMapperHelper.php
      function versioned_asset($path) {
          $mapper = app(\Symfony\Component\AssetMapper\AssetMapper::class);
          return $mapper->getUrl($path);
      }
      
      Usage:
      <link rel="stylesheet" href="{{ versioned_asset('css/app.css') }}">
      

2. Importmap for ES Modules

  • Pattern: Define entrypoints and external dependencies in config/asset_mapper.php:
    'import_map' => [
        'entrypoints' => [
            'app' => ['js/app.js'],
            'admin' => ['js/admin.js'],
        ],
        'imports' => [
            'react' => 'https://esm.sh/react@18',
            'lodash' => '/build/lodash.[hash].js',
        ],
    ],
    
  • Integration:
    • Dynamic Importmap: Use the asset-map:dump command to regenerate importmap.json after changes.
    • Blade Integration:
      @asset_mapper_importmap
      
      (Requires a custom Blade directive or Twig extension.)
    • CDN Fallback: Reference external libraries (e.g., React) via CDN in imports.

3. Development vs. Production

Environment Strategy Configuration
Development version_strategy: 'timestamp' Faster iteration, no cache-busting.
Production version_strategy: 'hash' Cache-busting, long-term caching.
Hot Reload asset-map:watch Run in dev: php artisan asset-map:watch.

4. Customizing Asset Processing

  • Pattern: Extend the AssetMapper to add pre-processing (e.g., minification, compression).
  • Example: Use a custom AssetMapper class:
    // app/Services/CustomAssetMapper.php
    namespace App\Services;
    
    use Symfony\Component\AssetMapper\AssetMapper;
    use Symfony\Component\AssetMapper\AssetMapperInterface;
    
    class CustomAssetMapper extends AssetMapper implements AssetMapperInterface {
        public function getUrl(string $path): string {
            // Add custom logic (e.g., minify CSS/JS)
            $url = parent::getUrl($path);
            return str_replace('.css', '.min.css', $url);
        }
    }
    
  • Register in AppServiceProvider:
    public function register() {
        $this->app->bind(\Symfony\Component\AssetMapper\AssetMapperInterface::class, \App\Services\CustomAssetMapper::class);
    }
    

5. Integration with Laravel Ecosystem

  • Laravel Mix/Vite: Use importmap.json as a replacement for mix-manifest.json for ES modules.
    // vite.config.js
    export default {
        build: {
            manifest: false, // Disable Vite's manifest if using importmap
        },
    };
    
  • Blade Directives: Create a custom directive to output the importmap:
    // app/Providers/BladeServiceProvider.php
    Blade::directive('asset_mapper_importmap', function () {
        return "<?php echo file_get_contents(public_path('build/importmap.json')); ?>";
    });
    
    Usage:
    <script type="importmap">
        @asset_mapper_importmap
    </script>
    

6. Handling Static Assets (CSS, Images, Fonts)

  • Pattern: Map all static assets to a single directory (e.g., resources/assets).
    'source_dirs' => [
        resource_path('assets/css'),
        resource_path('assets/js'),
        resource_path('assets/images'),
    ],
    
  • Usage:
    <!-- CSS -->
    <link rel="stylesheet" href="{{ asset('build/styles.[hash].css') }}">
    
    <!-- Images -->
    <img src="{{ asset('build/logo.[hash].png') }}" alt="Logo">
    

Gotchas and Tips

1. Common Pitfalls

Issue Solution
Assets not updating Clear public/build and run php artisan asset-map:dump --force.
Importmap missing entries Ensure entrypoints in config/asset_mapper.php match your JS files.
404 errors for assets Verify public_dir in config points to a writable directory.
Hash collisions Use version_strategy: 'timestamp' in dev to debug.
Circular imports Update config/asset_mapper.php to include all dependencies in imports.
Blade cache conflicts Clear Blade cache: php artisan view:clear.

2. Debugging Tips

  • Check the importmap:
    cat public/build/importmap.json
    
  • Enable verbose output:
    php artisan asset-map:dump --verbose
    
  • Inspect generated assets:
    ls -la public/build/
    
  • Test locally first: Use asset-map:watch in development to catch issues early.

3. Configuration Quirks

  • source_dirs:
    • Must be absolute paths (use resource_path() or public_path()).
    • Exclude files with .assetmapignore (similar to .gitignore).
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope