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

Vite Bundle Laravel Package

pentatrion/vite-bundle

Symfony bundle integrating Vite for easy asset loading. Provides Twig functions to render the right script and link tags for Vite dev server and production builds (including React dependency handling). Install via Composer and use vite_entry_* tags in templates.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require pentatrion/vite-bundle
    

    This auto-configures Symfony via a recipe, including:

    • Vite dev server routes (/build).
    • vite-plugin-symfony integration.
    • Default package.json/vite.config.js templates.
  2. Run Vite Dev Server

    npm install
    npm run dev
    
  3. Integrate Twig Tags Add these to your base template (e.g., base.html.twig):

    {% block stylesheets %}
        {{ vite_entry_link_tags('app') }}
    {% endblock %}
    
    {% block javascripts %}
        {{ vite_entry_script_tags('app') }}
    {% endblock %}
    

    Replace 'app' with your Vite entry point (defined in vite.config.js).

  4. Verify

    • Dev mode: Assets load via Vite’s HMR.
    • Prod mode: Builds to /public/build/ (configured in vite.config.js).

First Use Case: Migrating from Webpack Encore

  1. Backup and replace assets/ and package.json:
    mv assets assets.bak
    composer remove symfony/webpack-encore-bundle
    mv assets.bak assets
    
  2. Update vite.config.js:
    import symfonyPlugin from 'vite-plugin-symfony';
    
    export default {
        plugins: [symfonyPlugin()],
        build: {
            rollupOptions: {
                input: {
                    app: './assets/app.js', // Match Twig entry point
                },
            },
        },
    };
    
  3. Replace Twig tags (see above).

Implementation Patterns

Workflow: Asset Management

  1. Entry Points Define entries in vite.config.js as an object:

    build: {
        rollupOptions: {
            input: {
                app: './assets/app.js',
                admin: './assets/admin.js',
            },
        },
    }
    

    Use in Twig:

    {{ vite_entry_link_tags('admin') }}
    {{ vite_entry_script_tags('app') }}
    
  2. Environment-Specific Configs Use mode in vite.config.js:

    export default defineConfig(({ mode }) => ({
        plugins: [symfonyPlugin({ enabled: mode !== 'production' })],
    }));
    
  3. Dynamic Imports For lazy-loaded assets (e.g., Stimulus controllers):

    // vite.config.js
    plugins: [
        symfonyPlugin({
            stimulus: {
                controllersDir: './assets/controllers',
            },
        }),
    ];
    

Integration Tips

  1. Symfony UX (React/Vue)

    • Install @symfony/ux-react or @symfony/ux-vue alongside.
    • Ensure vite.config.js includes:
      plugins: [
          symfonyPlugin(),
          react(), // or vue()
      ],
      
  2. Legacy Browser Support

    • Use vite-plugin-symfony's legacy option:
      symfonyPlugin({
          legacy: {
              build: './assets/legacy.js',
          },
      });
      
    • Twig tags auto-generate <script nomodule> fallbacks.
  3. Environment Variables Expose Symfony env vars to Vite:

    symfonyPlugin({
        exposedEnvVars: ['APP_ENV', 'APP_DEBUG'],
    });
    

    Access in JS:

    import.meta.env.APP_ENV;
    
  4. Custom Build Output Override outDir in vite.config.js:

    build: {
        outDir: '../public/custom-build',
    }
    

    Update Symfony’s asset path in config/packages/pentatrion_vite.yaml:

    pentatrion_vite:
        build_directory: '/custom-build'
    

Gotchas and Tips

Pitfalls

  1. Missing manifest.json in Dev Mode

    • Issue: ViteBundle expects manifest.json for prod builds but removes it in dev.
    • Fix: Ensure npm run dev is running when accessing dev assets. Use npm run build for prod.
  2. CORS Errors in Dev

    • Issue: Vite dev server may block Symfony’s /build proxy.
    • Fix: Configure vite.config.js:
      server: {
          proxy: {
              '/build': {
                  target: 'https://symfony.local',
                  changeOrigin: true,
              },
          },
      }
      
  3. Stimulus HMR Not Working

    • Issue: Controllers not reloading on changes.
    • Fix: Explicitly opt into HMR:
      symfonyPlugin({
          stimulus: {
              hmr: true,
          },
      });
      
  4. TypeScript Errors

    • Issue: @hotwired/stimulus types conflict.
    • Fix: Extend types in vite.config.js:
      declare module '@hotwired/stimulus' {
          interface Stimulus {
              controllers: Record<string, any>;
          }
      }
      

Debugging

  1. Asset Not Found

    • Check npm run dev is running.
    • Verify vite.config.js input matches Twig entry points.
    • Clear Symfony cache:
      php bin/console cache:clear
      
  2. Prod Build Fails

    • Ensure outDir is writable:
      chmod -R 775 public/build
      
    • Check manifest.json exists in public/build.
  3. Twig Functions Missing

    • Reinstall the bundle:
      composer require pentatrion/vite-bundle --update-with-dependencies
      
    • Clear Twig cache:
      php bin/console cache:clear --env=prod
      

Extension Points

  1. Custom Vite Config Override default config via config/packages/pentatrion_vite.yaml:

    pentatrion_vite:
        vite_options:
            build:
                emptyOutDir: true
    
  2. Preload Assets Use Symfony’s PreloadAssetsEventListener:

    // src/EventListener/PreloadAssetsListener.php
    public function onPreloadAssets(PreloadAssetsEvent $event) {
        $event->addAsset('app', 'vite:///assets/app.js');
    }
    
  3. Legacy Asset Handling For non-modern browsers, extend vite-plugin-symfony:

    symfonyPlugin({
        legacy: {
            entry: './assets/legacy.js',
            build: './assets/legacy-built.js',
        },
    });
    

Pro Tips

  1. Vite 7+ Compatibility Use vite-bundle@^8.2.0 for Vite 7 support:

    composer require pentatrion/vite-bundle:^8.2.0
    
  2. HTTPS in Dev For local HTTPS (e.g., with Symfony CLI):

    symfony serve --no-tls
    

    Configure Vite to trust self-signed certs:

    server: {
        https: {
            key: './path/to/key.pem',
            cert: './path/to/cert.pem',
        },
    }
    
  3. Monorepo Support Use vite-plugin-symfony’s root option:

    symfonyPlugin({
        root: '../monorepo-packages',
    });
    
  4. Profiler Integration Enable Vite’s profiler in vite.config.js:

    plugins: [
        symfonyPlugin({
            profiler: true,
        }),
    ];
    

    View stats at /_profiler/vite.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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