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

bechir/vite-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bechir/vite-bundle
    yarn add --dev vite-fait
    

    Enable the bundle in config/bundles.php and configure config/packages/bechir_vite.yaml:

    bechir_vite:
      output_path: '%kernel.project_dir%/public/dist'
    
  2. First Use Case:

    • Create vite.config.js in your project root with a basic config:
      const ViteFait = require('vite-fait');
      module.exports = ViteFait
        .setRoot('assets')
        .setOutputPath('../public/dist')
        .addEntry('app', './assets/app.js')
        .getViteConfig();
      
    • Run yarn dev (or npm run dev) to generate assets in public/dist.
  3. Symfony Integration:

    • Reference the generated files in your Twig templates:
      <script type="module" src="{{ asset('dist/app.js') }}"></script>
      

Implementation Patterns

Workflows

  1. Development Workflow:

    • Use yarn dev (or npm run dev) for hot module replacement (HMR) during development.
    • Vite’s native HMR works seamlessly with Symfony’s Twig templates (no extra config needed).
  2. Production Build:

    • Run yarn build (or npm run build) to generate optimized assets.
    • The bundle copies files from public/dist to Symfony’s public/ directory (if configured).
  3. Multi-Entry Points:

    • Define separate entry points for frontend/backend (e.g., app.js, admin.js) in vite.config.js:
      ViteFait
        .addEntry('app', './assets/app.js')
        .addEntry('admin', './assets/admin/app.js');
      
    • Load them conditionally in Twig:
      {% if app.user.isAdmin %}
        <script type="module" src="{{ asset('dist/admin.js') }}"></script>
      {% else %}
        <script type="module" src="{{ asset('dist/app.js') }}"></script>
      {% endif %}
      
  4. Asset Versioning:

    • Leverage Vite’s built-in asset hashing (e.g., app.[hash].js). Cache-busting works out-of-the-box.
  5. Symfony Asset Integration:

    • Use {{ asset() }} in Twig for generated files (e.g., {{ asset('dist/app.js') }}).
    • For CSS, reference files directly:
      <link rel="stylesheet" href="{{ asset('dist/app.css') }}">
      

Integration Tips

  • Webpack Encore Migration: Replace webpack.config.js with vite.config.js. The bundle bridges Vite’s output to Symfony’s asset pipeline. Example migration:

    // Before (Encore)
    Encore
      .setOutputPath('public/build/')
      .addEntry('app', './assets/app.js');
    
    // After (Vite)
    ViteFait
      .setOutputPath('../public/build/')
      .addEntry('app', './assets/app.js');
    
  • Environment-Specific Configs: Use Vite’s mode flag to switch configs (e.g., yarn dev --mode=staging). Example in vite.config.js:

    const mode = process.env.VITE_MODE || 'development';
    if (mode === 'production') {
      ViteFait.setBase('/prod-assets/');
    }
    
  • TypeScript Support: Add TypeScript via vite.config.js:

    ViteFait.setInput('assets/ts/app.ts').setOutput('app.js');
    

    Install dependencies:

    yarn add --dev typescript @types/node
    

Gotchas and Tips

Pitfalls

  1. Output Path Conflicts:

    • Ensure bechir_vite.output_path in config/packages/bechir_vite.yaml matches the path in vite.config.js (setOutputPath).
    • Fix: Verify paths are relative to the project root (e.g., ../public/dist vs. public/dist).
  2. Missing vite-fait:

    • Forgetting to install vite-fait (yarn add --dev vite-fait) will break the bundle.
    • Fix: Run the install command after composer require.
  3. Twig Asset Paths:

    • Using {{ asset('dist/app.js') }} in development may fail if Vite’s HMR isn’t properly proxied.
    • Fix: Configure Symfony’s dev server to proxy /dist to Vite’s dev server (see ViteFait docs).
  4. Caching Issues:

    • Hard refreshes in development may not trigger HMR due to cached assets.
    • Fix: Use yarn dev --force or clear browser cache.
  5. Symfony Asset Controller:

    • The bundle doesn’t override Symfony’s assets:install command. Manually copy files from dist/ to public/ in production:
      cp -r public/dist/* public/
      

Debugging

  1. Vite Errors:

    • Check the browser console for Vite-specific errors (e.g., missing dependencies).
    • Run yarn dev --debug for verbose logs.
  2. Symfony Logs:

    • Enable Symfony’s debug mode (APP_DEBUG=1) to catch PHP-level issues (e.g., missing bundle config).
  3. Network Tab:

    • Verify Vite’s dev server is running on http://localhost:3000 (default) and assets are loaded from there during development.

Extension Points

  1. Custom Vite Plugins:

    • Extend vite.config.js with additional plugins (e.g., @vitejs/plugin-react):
      const { defineConfig } = require('vite');
      const react = require('@vitejs/plugin-react');
      module.exports = defineConfig({
        plugins: [react()],
        ...ViteFait.getViteConfig(),
      });
      
  2. Symfony Event Listeners:

    • Trigger builds post-deploy via Symfony events (e.g., kernel.terminate):
      // src/EventListener/ViteBuildListener.php
      use Symfony\Component\HttpKernel\Event\TerminateEvent;
      use Symfony\Component\HttpKernel\KernelEvents;
      
      class ViteBuildListener {
          public function onTerminate(TerminateEvent $event) {
              if ($event->isMainRequest() && $event->getRequest()->getPathInfo() === '/build') {
                  shell_exec('yarn build');
              }
          }
      }
      
      Register in services.yaml:
      services:
          App\EventListener\ViteBuildListener:
              tags:
                  - { name: kernel.event_listener, event: kernel.terminate, method: onTerminate }
      
  3. Dynamic Entry Points:

    • Generate vite.config.js dynamically based on Symfony’s routes:
      // src/Kernel.php
      public function getViteEntries(): array {
          return [
              'app' => 'assets/app.js',
              'admin' => 'assets/admin/app.js',
          ];
      }
      
      Use in vite.config.js:
      const entries = JSON.parse(<?= json_encode($kernel->getViteEntries()) ?>);
      Object.entries(entries).forEach(([name, path]) => {
          ViteFait.addEntry(name, path);
      });
      
  4. Environment Variables:

    • Pass Symfony’s %env% variables to Vite via .env:
      echo "VITE_APP_ENV=$APP_ENV" >> .env
      
      Access in JavaScript:
      console.log(import.meta.env.VITE_APP_ENV);
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor