All Projects → lhapaipai → vite-bundle

lhapaipai / vite-bundle

Licence: MIT license
Integration with your Symfony app & Vite

Programming Languages

PHP
23972 projects - #3 most used programming language
javascript
184084 projects - #8 most used programming language
CSS
56736 projects

Projects that are alternatives of or similar to vite-bundle

breadcrumb-bundle
Symfony bundle for easy breadcrumbs management
Stars: ✭ 26 (-53.57%)
Mutual labels:  bundle, symfony-bundle
AtoumBundle
This bundle provides a simple integration of atoum into Symfony 2.
Stars: ✭ 44 (-21.43%)
Mutual labels:  bundle, symfony-bundle
awsBundle
Symfony AWS Bundle (supports Symfony 2, 3 and 4)
Stars: ✭ 18 (-67.86%)
Mutual labels:  bundle, symfony-bundle
connect-bundle
No description or website provided.
Stars: ✭ 35 (-37.5%)
Mutual labels:  bundle, symfony-bundle
SonataFormatterBundle
Symfony SonataFormatterBundle
Stars: ✭ 78 (+39.29%)
Mutual labels:  bundle, symfony-bundle
NucleosDompdfBundle
📜 This bundle provides a wrapper for using dompdf inside symfony.
Stars: ✭ 29 (-48.21%)
Mutual labels:  bundle, symfony-bundle
socketio
No description or website provided.
Stars: ✭ 23 (-58.93%)
Mutual labels:  bundle, symfony-bundle
SonataDoctrineMongoDBAdminBundle
Symfony Sonata / Integrate Doctrine MongoDB ODM into the SonataAdminBundle
Stars: ✭ 64 (+14.29%)
Mutual labels:  bundle, symfony-bundle
DynamicParametersBundle
[UNMAINTAINED] Runtime retrieval of parameters from environment variables for Symfony
Stars: ✭ 42 (-25%)
Mutual labels:  bundle, symfony-bundle
wordpress-bundle
Use Wordpress and Symfony together using a Symfony bundle
Stars: ✭ 30 (-46.43%)
Mutual labels:  bundle, symfony-bundle
hashed-asset-bundle
Apply an asset version based on a hash of the asset for symfony/asset
Stars: ✭ 24 (-57.14%)
Mutual labels:  bundle, symfony-bundle
FkrCssURLRewriteBundle
A small assetic filter for symfony to fix all url paths at css documents to correct urls
Stars: ✭ 33 (-41.07%)
Mutual labels:  bundle, symfony-bundle
jsonrpc-bundle
JSON-RPC server for Symfony: exposes services registered in the service container as JSON-RPC-webservices
Stars: ✭ 31 (-44.64%)
Mutual labels:  bundle, symfony-bundle
LiipSoapRecorderBundle
[DEPRECATED] Recorder/Player for SOAP communications
Stars: ✭ 12 (-78.57%)
Mutual labels:  bundle, symfony-bundle
LiipImagineSerializationBundle
Provides integration between LiipImagineBundle and JMSSerializerBundle
Stars: ✭ 24 (-57.14%)
Mutual labels:  bundle, symfony-bundle
BeelabTagBundle
🏷 A simple implementation of tags for Symfony and Doctrine ORM
Stars: ✭ 45 (-19.64%)
Mutual labels:  bundle, symfony-bundle
SonataDashboardBundle
[Abandoned] Provides a Dashboard management through container and block services
Stars: ✭ 17 (-69.64%)
Mutual labels:  bundle, symfony-bundle
stampie-bundle
stampie.github.io/
Stars: ✭ 26 (-53.57%)
Mutual labels:  bundle, symfony-bundle
OpcacheBundle
Displays the PHP OPcache status in the Symfony profiler toolbar.
Stars: ✭ 21 (-62.5%)
Mutual labels:  bundle, symfony-bundle
LexikMailerBundle
This Symfony2 bundle allow you to manage some HTML email templates stored in your database. Templates are written with Twig and use I18N. You can also create some layouts to decorate your email.
Stars: ✭ 81 (+44.64%)
Mutual labels:  bundle, symfony-bundle

Symfony logo

ViteBundle : Symfony integration with Vite

This bundle helping you render all of the dynamic script and link tags needed. Essentially, he provides two twig functions to load the correct scripts into your templates.

Installation

Before you start, make sure you don't have a package.json file otherwise, ff you come from Webpack Encore, check the migration documentation.

Install the bundle with :

composer require pentatrion/vite-bundle
npm install

# start your vite dev server
npm run dev

Add this twig functions in any template or base layout where you need to include a JavaScript entry.

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

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

if you experience unwanted reloads of your application, read the section https/http in development.

if you are using React, you have to add this option in order to have FastRefresh.

{{ vite_entry_script_tags('app', { dependency: 'react' }) }}

If you want to install the bundle without the community recipe, check the manual installation.

Bundle Configuration

If you change some properties in your vite.config.js file, you probably need to create a config/packages/pentatrion_vite.yaml file to postpone these changes. it concerns server.host, server.port, server.https and build.outdir (and also base).

default configuration

# config/packages/pentatrion_vite.yaml
pentatrion_vite:
    # Base public path when served in development or production
    base: /build/
    # path to the web root relative to the Symfony project root directory
    public_dir: /public
    # Server options
    server:
        host: localhost
        port: 5173
        https: false

Symfony Asset Component

Whenever you build your Vite app, three configuration files are generated in your output folder (default location: public/build/): manifest.json (generated by vite core), entrypoints.json and assets.json (generated by vite-plugin-symfony).

The manifest.json file is needed to get the versioned filename of assets files, like font files or image files and css/js files

{
  "assets/images/avatar.jpg": "/build/avatar.0511b7a8.jpg",
  "app.css": "/build/app.8a53d9f7.css"
}

so you can use Symfony's asset component and its asset function to take advantage of this file. To be able to use this during development you will have to use ViteAssetVersionStrategy.

# config/packages/framework.yaml
framework:
    assets:
        version_strategy: 'Pentatrion\ViteBundle\Asset\ViteAssetVersionStrategy'

You can also use the asset twig function by specifing your asset file path relative to your root path (for compatibility reason with vite generated manifest file) specified in your vite.config.js

<body>
    <img src="{{ asset('assets/images/avatar.jpg') }}" />
</body>

Vite config

For the transparency, I decided not to create an overlay of the config file vite.config.js. However some config properties must not be modified for the bundle to work.

// vite.config.js
import {defineConfig} from "vite";
import symfonyPlugin from "vite-plugin-symfony";

/* if you're using React */
// import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        /* react(), // if you're using React */
        symfonyPlugin(),
    ],
    root: ".",      /* DO NOT CHANGE */

    /* your outDir prefix relative to web path */
    base: "/build/",

    /* By default, Vite will copy all assets in /public to the build directory. */
    /* no longer needed because your web server already does it */
    publicDir: false,

    build: {
        assetsDir: "",     /* DO NOT CHANGE */
        emptyOutDir: true, /* DO NOT CHANGE */
        manifest: true,    /* DO NOT CHANGE */
        outDir: "./public/build",
        rollupOptions: {
            input: {
                app: "./assets/app.ts", /* relative to the root option */

                theme: "./assets/theme.css" /* you can provide css file and
                it will be directly inserted in a link tag to prevent FOUC with the development server.
                note : still add the 2 twig functions vite_entry_link_tags / vite_entry_script_tags
                even if the entry point is a css file because ViteJs may need to insert his js code to
                enable the hmr */
            },
        }
    },
});

Usage tips

Dependency Pre-Bundling

Initially in a Vite project, index.html is the entry point to your application. When you run your dev serve, Vite will crawl your source code and automatically discover dependency imports.

Because we don't have any index.html, Vite can't do this Pre-bundling step when he starts but when you browse a page where he finds a package he does not already have cached. Vite will re-run the dep bundling process and reload the page.

this behavior can be annoying if you have a lot of dependencies because it creates a lot of page reloads before getting to the final render.

you can limit this by declaring in the vite.config.js the most common dependencies of your project.

// vite.config.js

export default defineConfig({
    server: {
        //Set to true to force dependency pre-bundling.
        force: true,
    },
    // ...
    optimizeDeps: {
        include: ["my-package"],
    },
});

One file by entry point

Vite try to split your js files into multiple smaller files shared between entry points. In some cases, it's not a good choise and you can prefer output one js file by entry point.

// vite.config.js

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: undefined,
      },
    },
  },
});

https / http in Development

By default, your Vite dev server don't use https and can cause unwanted reload if you serve your application with https (probably due to invalid certificates ). Configuration is easier if you develop your application without https.

npm run dev
symfony serve --no-tls

browse : http://127.0.0.1:8000

if you still want to use https you will need to generate certificates for your Vite dev server.

you can use mkcert : https://github.com/FiloSottile/mkcert

mkcert -install
mkcert -key-file certs/vite.key.pem -cert-file certs/vite.crt.pem localhost 127.0.0.1
// vite.config.js
import fs from "fs";

export default defineConfig({

    // ...
    server: {
        https: {
          key: fs.readFileSync('certs/vite.key.pem'),
          cert: fs.readFileSync('certs/vite.crt.pem'),
        },
        cors: true
    },
});
# config/packages/pentatrion_vite.yaml
pentatrion_vite:
    # Server options
    server:
        https: true
npm run dev
symfony serve

browse : https://127.0.0.1:8000

Dependency injection

if you want more control (like creating custom Twig functions), you can use dependency injection with EntrypointRenderer / EntrypointsLookup.

use Twig\Extension\AbstractExtension;
use Pentatrion\ViteBundle\Asset\EntrypointRenderer;
use Pentatrion\ViteBundle\Asset\EntrypointsLookup;

class YourTwigExtension extends AbstractExtension
    public function __contruct(
        private EntrypointsLookup $entrypointsLookup,
        private EntrypointRenderer $entrypointsRenderer
    ) {
        // ...
    }
}

Migration from v0.2.x to v1.x

In version v0.2.x, you have to specify your entry points in an array in your vite.config.js file. in v1.x you need to specify your entry points in an object.

-input: ["./assets/app.js"],
+input: {
+  app: "./assets/app.js"
+},

this way you need to specify the named entry point in your twig functions.

-{{ vite_entry_script_tags('app.js') }}
+{{ vite_entry_script_tags('app') }}
-{{ vite_entry_link_tags('app.js') }}
+{{ vite_entry_link_tags('app') }}

In v1.x, your symfonyPlugin is a function and come from the vite-plugin-symfony package.

+ import symfonyPlugin from 'vite-plugin-symfony';

    // ...
    plugins: [
        /* react(), // if you're using React */
-       symfonyPlugin,
+       symfonyPlugin(),
    ],

How this bundle works

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

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

would render in dev:

<!--Nothing with vite_entry_link_tags('app') -->

<!-- vite_entry_script_tags('app') -->
<script src="http://localhost:3000/build/@vite/client" type="module"></script>
<script src="http://localhost:3000/build/app.js" type="module"></script>

would render in prod:

<!-- vite_entry_link_tags('app') -->
<link rel="stylesheet" href="/build/app.[hash].css" />
<link rel="modulepreload" href="/build/vendor.[hash].js" />

<!-- vite_entry_script_tags('app') -->
<script src="/build/app.[hash].js" type="module"></script>

In development environment, the bundle also acts as a proxy by forwarding requests that are not intended for it to the Vite dev server.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].