Giter Club home page Giter Club logo

vite-bundle's Introduction

Symfony logo

ViteBundle : Symfony integration with Vite

Important

This repository is a "subtree split": a read-only subset of that main repository symfony-vite-dev which delivers to packagist only the necessary code.

Important

If you want to open issues, contribute, make PRs or consult examples you will have to go to the symfony-vite-dev repository.

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

Installation

Install the bundle with:

composer require pentatrion/vite-bundle
npm install

# start your vite dev server
npm run dev

Add these 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') }}

    {# if you are using React, you have to replace with this #}
    {{ vite_entry_script_tags('app', { dependency: 'react' }) }}
{% endblock %}

Read the Docs to Learn More.

Ecosystem

Package Description
vite-plugin-symfony Vite plugin (read-only)
symfony-vite-dev Package for contributors

License

MIT.

vite-bundle's People

Contributors

andyexeter avatar bitbirddev avatar blackskyliner avatar justdylan23 avatar lhapaipai avatar maamri95 avatar magiczne avatar nanosector avatar plfort avatar skmedix avatar thor-juhasz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-bundle's Issues

"unable to map generatedFile" error

Hello, upon upgrading from 0.7 to 3.3, I get the following when run vite build:

unable to map generatedFile { inputType: 'js', inputRelPath: 'public/js/src/admin.js' } undefined undefined {
  '_assets/icons-public-28183a31.svg': 'assets/icons-public-28183a31.svg',
  '_assets/logo-331be2df.svg': 'assets/logo-331be2df.svg',
  '_assets/logo-icon-e794f0b7.svg': 'assets/logo-icon-e794f0b7.svg',
  '_assets/icons-admin-c8aafe95.svg': 'assets/icons-admin-c8aafe95.svg',
  '_assets/admin-a6bbdf0e.css': 'assets/admin-a6bbdf0e.css',
  '_assets/public-0d9cb2fb.css': 'assets/public-0d9cb2fb.css',
  'js/src/admin/admin_dashboard/index.vue': 'assets/index-3bb643c9.js',
  '_assets/user.validation-286b7721.js': 'assets/user.validation-286b7721.js',
  'js/src/admin/user/add.vue': 'assets/add-cce891e5.js',
  'js/src/admin/user_profile_edit/index.vue': 'assets/index-95fe6fae.js',
  'js/src/admin/user_profile_edit/profile.vue': 'assets/profile-0ad9d555.js',
  'js/src/admin/user_recover/reset.vue': 'assets/reset-bc0030f5.js',
  'js/src/admin/user/index.vue': 'assets/index-419d3f02.js',
  '_assets/user.mutation-699bf025.js': 'assets/user.mutation-699bf025.js',
  'js/src/admin/user_recover/initiate.vue': 'assets/initiate-d7121e3f.js',
  'js/src/admin/user_profile_edit/password.vue': 'assets/password-368f5a36.js',
  'js/src/admin/login/index.vue': 'assets/index-0cebb5f6.js',
  'js/src/common/modal.vue': 'assets/modal-547f6a5d.js',
  'js/src/admin/user/edit.vue': 'assets/edit-ff7feac0.js',
  'js/src/admin/user_verify/index.vue': 'assets/index-4118f462.js',
  'js/src/admin/admin_delete/index.vue': 'assets/index-fdf04cf8.js',
  'js/src/admin/user_recover/index.vue': 'assets/index-bb4cc612.js',
  'js/src/admin/user/list.vue': 'assets/list-79091ece.js',
  'js/src/common/local_time.vue': 'assets/local_time-02f148eb.js',
  'js/src/admin/sector/index.vue': 'assets/index-abb6db80.js',
  'js/src/admin/organization/index.vue': 'assets/index-51d254a4.js',
  'js/src/admin/sector/list.vue': 'assets/list-9f1199d5.js',
  '_assets/sector.query-6f039c1d.js': 'assets/sector.query-6f039c1d.js',
  'js/src/admin/error/403.vue': 'assets/403-07a2504c.js',
  '_assets/organization.query-4bbfc215.js': 'assets/organization.query-4bbfc215.js',
  '_assets/debounce-0da8c87b.js': 'assets/debounce-0da8c87b.js',
  '_assets/sector.validation-223b603b.js': 'assets/sector.validation-223b603b.js',
  'js/src/admin/error/404.vue': 'assets/404-b441e070.js',
  'js/src/admin/sector/add.vue': 'assets/add-10bbbdd9.js',
  'js/src/admin/pattern_library/index.vue': 'assets/index-2ea7354b.js',
  'js/src/admin/organization/edit.vue': 'assets/edit-3a1f67fe.js',
  '_assets/pagination-21601ef8.js': 'assets/pagination-21601ef8.js',
  'js/src/common/password_score.vue': 'assets/password_score-1c26e8c7.js',
  '_assets/form-eddff054.js': 'assets/form-eddff054.js',
  'js/src/admin/organization/add.vue': 'assets/add-ad9f285d.js',
  'js/src/admin/sector/edit.vue': 'assets/edit-d7b17b6a.js',
  '_assets/field_password_with_errors-12fd7312.js': 'assets/field_password_with_errors-12fd7312.js',
  'js/src/admin/organization/list.vue': 'assets/list-e70e7bce.js',
  '_assets/cloneDeep-a15c3f3b.js': 'assets/cloneDeep-a15c3f3b.js',
  '_assets/index-1fba44e8.js': 'assets/index-1fba44e8.js',
  '_assets/field_email-417ca71b.js': 'assets/field_email-417ca71b.js',
  '_assets/v4-a960c1f4.js': 'assets/v4-a960c1f4.js',
  '_assets/field_input-c7ec07ec.js': 'assets/field_input-c7ec07ec.js',
  '_assets/isArrayLike-0fb0184d.js': 'assets/isArrayLike-0fb0184d.js',
  '_assets/_Uint8Array-8b8e6049.js': 'assets/_Uint8Array-8b8e6049.js',
  'js/src/public/safety_training_claim/index.vue': 'assets/index-f3d61d1e.js',
  'js/src/public/error/404.vue': 'assets/404-2e3890e3.js',
  '_assets/validators-13c9aa22.js': 'assets/validators-13c9aa22.js',
  '_assets/field_radios-c68a6137.js': 'assets/field_radios-c68a6137.js',
  'js/src/public/error/403.vue': 'assets/403-cd820219.js',
  '_assets/index-95a67cf9.js': 'assets/index-95a67cf9.js',
  '_assets/index-dd9de1d9.js': 'assets/index-dd9de1d9.js',
  '_assets/field_address-3c9710ad.js': 'assets/field_address-3c9710ad.js',
  'js/src/public.js': 'assets/public-cce894a5.js',
  '_assets/useMachine-dccd0541.js': 'assets/useMachine-dccd0541.js',
  'js/src/admin.js': 'assets/admin-54a7f776.js',
  '_assets/lodash-fe689b24.js': 'assets/lodash-fe689b24.js',
  '_assets/user-6bfa1d24.js': 'assets/user-6bfa1d24.js',
  '_assets/admin_button-61bc5444.js': 'assets/admin_button-61bc5444.js'
}

My vite config:

import { defineConfig } from 'vite';
import { fileURLToPath, URL } from 'node:url';
import basicSslPlugin from '@vitejs/plugin-basic-ssl';
import vuePlugin from '@vitejs/plugin-vue';
import graphqlPlugin from '@rollup/plugin-graphql';
import manifestSRIPlugin from 'vite-plugin-manifest-sri';
import symfonyPlugin from 'vite-plugin-symfony';
import liveReload from 'vite-plugin-live-reload';
import dns from 'dns';

dns.setDefaultResultOrder('verbatim');

export default defineConfig({
    root: 'public',
    // by default Vite looks in the root
    envDir: '../',
    plugins: [
        basicSslPlugin(),
        vuePlugin(),
        graphqlPlugin(),
        manifestSRIPlugin(),
        symfonyPlugin(),
        liveReload([
            // edit live reload paths according to your source code
            __dirname + '/(templates)/**/*.php',
        ]),
    ],
    build: {
        outDir: 'build',
        rollupOptions: {
            input: {
                admin: './public/js/src/admin.js',
                public: './public/js/src/public.js',
            },
        },
    },
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./public/js/src', import.meta.url)),
        },
        // the default plus .vue
        extensions: ['.vue', '.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'],
    },
    css: {
        devSourcemap: true,
    },
    server: {
        host: true,
        port: 9039,
        origin: 'https://localhost:9039',
        strictPort: true,
    },
});

I've tried digging and messing around and can't figure out exactly what's going on other than that it's something related to the entrypoints.json generation.

What am I doing wrong? (I'm fairly new to Vite...so could be anything.)
Let me know if you need any more info.

The routing file "pentatrion_vite.yaml" contains unsupported keys

SalΓ»t,

after updating to the latest version (2.2.1) with this yaml file according to the readme's "Bundle Configuration"

_pentatrion_vite:
    # Base public path when served in development or production
    prefix: /public/build
    # path to the web root relative to the Symfony project root directory
    public_dir: /public
    script_attributes:
        # you can define your attributes that you want to apply
        # for all your script tags
    link_attributes:
        # you can define your attributes that you want to apply
        # for all your link tags
    resource: "@PentatrionViteBundle/Resources/config/routing.yaml"

I get an elaborate error message from Symfony or running a composer update

The routing file "D:...\config/routes/dev/pentatrion_vite.yaml"
contains unsupported keys for "_pentatrion_vite": "public_dir", "script_attributes", "link_attributes".
Expected one of: "resource", "type", "prefix", "path", "host", "schemes", "methods", "defaults", "requirements", "options", "condition", "controller", "name_prefix", "trailing_slash_on_root", "locale", "format", "utf8", "exclude", "stateless"
in D:...\config/routes/dev/pentatrion_vite.yaml
(which is being imported from "D:...\src\Kernel.php").

I have to remove all but prefix to make it run.

Running composer recipes pentatrion/vite-bundle responds with "up to date"

I "discovered" public_dir digging through the former release, and adding it also resulted in an error.

Γ  la prochaine

Loading Build assets when in dev mode

We are wondering since our backend-developers don't make changes to the JS and SCSS and thus don't really need to do a yarn dev if it is possible to rewrite the config to not load assets from localhost:3000 but directly from the generated (via yarn build) assets.

Not sure if this is a config we have to make in the config/packages/pentatrion_vite.yaml or the vite.config.js.

Usage with asset

It would be great to be able to use the asset symfony helper with the bundle.
The way it works usually is by reading a manifest file in the build directory in order to resolve the asset path.
Not sure if it is possible to generate such a file with vite but it would be awesome.

Feature Request: Add Event to allow for dynamic attributes

The injected script and link tags currently can be extended with custom attributes using the script_attributes and link_attributes configuration options.
This is great for simple and static values but won't work if some computation is neccessary before specifying the attributes value.
I would propose adding a RenderAssetTagEvent similar to webpack-encore-bundle.
Otherwise it's impossible for me to add a nonce attribute with a dynamic value if I understand correctly.

wdyt?

Usage example

<?php

namespace App\EventSubscriber;

use App\Service\NonceService;
use Pentatrion\ViteBundle\Event\RenderAssetTagEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ViteTagsSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly NonceService $nonceService,
    ) {}

    public static function getSubscribedEvents(): array
    {
        return [
            RenderAssetTagEvent::class => 'onRenderAssetTag',
        ];
    }

    public function onRenderAssetTag(RenderAssetTagEvent $event): void
    {
        if ($event->isScriptTag()) {
            $event->setAttributes([
                'defer' => true,
                'nonce' => $this->nonceService->getNonce(),
            ]);
        }
    }
}

CSP errors in production

I use

{% block javascripts %}
    {{ vite_entry_script_tags('global', {attr: {nonce: csp_nonce}}) }}
{% endblock %}

and it works for all of my <script> tags. But when on production, the CSP blocks some of vite's own scripts. The error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'strict-dynamic' 'nonce-XktWXbolcLTNY5qxqQDvKOWbJj7vL5drDyBvdb3HMKU'". Either the 'unsafe-inline' keyword, a hash ('sha256-BoFUHKsYhJ9tbsHugtNQCmnkBbZ11pcW6kZguu+T+EU='), or a nonce ('nonce-...') is required to enable inline execution.

and these are the blocked scripts on the page:

<!-- DETECT_MODERN_BROWSER_CODE --><script type="module">try{import.meta.url;import("_").catch(()=>1);}catch(e){}window.__vite_is_modern_browser=true;</script>

   <!-- DYNAMIC_FALLBACK_INLINE_CODE --><script type="module">
       (function() {
           if (window.__vite_is_modern_browser) return;
           console.warn("vite: loading legacy build because dynamic import or import.meta.url is unsupported, syntax error above should be ignored");
           var legacyPolyfill = document.getElementById("vite-legacy-polyfill")
           var script = document.createElement("script");
           script.src = legacyPolyfill.src;
           script.onload = function() {
               document.querySelectorAll("script.vite-legacy-entry").forEach(function(elt) {
                   System.import(elt.getAttribute("data-src"));
               });
           };
           document.body.appendChild(script);
       })();
   </script>

Not sure if this post should be moved here: https://github.com/vitejs/vite/issues

`assetsInlineLimit` must be set to 0 by default

Hello there,

I think the build.assetsInlineLimit parameter should be set to 0 by default. Or the documentation should mention it.

Otherwise, even with import.meta.glob(["../images/**"]);, all assets less than 4kb will be inlined, and will not be available in the manifest and build folder. {{ asset('assets/images/small-asset-less-than-4kb.png') }} will fail.

Thanks for this very useful bundle, and a great and clean documentation !

Broken path on Windows - easy to fix

Using this bundle under Windows creates an issue where windows has backward slashes, while generally forward slashes should be used. Thus running into the issue below:

$ vite
C:\Users\Mossshine\intranet-extended\assets\app.ts
C:/Users/Mossshine/intranet-extended/assets
Entry points must be inside Vite root directory

at configResolver.ts line 78

Changing configResolver.ts line 75 from

const entryAbsolutePath = resolve(cwd(), entryPath);

to

const entryAbsolutePath = resolve(cwd(), entryPath).replace(/\\/g, '/');

fixes this issue.

Relative Assets in SASS aren't resolved correctly

Hey there,

There seems to be an issue in this bundle and/or its Vite configuration with relative asset paths in SASS.

With a directory structure like this:

assets
β”œβ”€β”€ app.js
β”œβ”€β”€ images
β”‚Β Β  └── vite.svg
└── styles
    β”œβ”€β”€ pages
    β”‚Β Β  └── home.scss
    └── style.scss

And home.scss containing this:

#app {
  width: 410px;
  height: 404px;
  background-image: url('../../images/vite.svg');
}

The background image does not load.

However, if you change the background image URL to ../images/vite.svg then it does load - but this is incorrect because images/ is 2 levels above styles/pages.

This used to be an issue in Vite itself, but was recently fixed in v3.2.3

I have created two demo projects to help debug this issue:

This is a standard Vite project, showing that the path is resolved correctly: https://stackblitz.com/edit/vitejs-vite-2btrkm

And this is a standard Symfony 6.1 project with this bundle installed: https://github.com/andyexeter/vite-bundle-issue-demo

If you install and run the Symfony project you'll see that the background image does not display unless you change the path to the incorrect one.

Vite controller is now useless

The goal of the vite controller is to proxy assets calls to the dev server.
It is not necessary anymore as vite offer an option to change the path of assets.

Configuration example:

export default defineConfig({
    ...
    server: {
        origin: 'https://localhost:3000',
        ...
    }

With this configuration, in development, the assets will be serve with the correct path.

Roadmap v1

Hi @lhapaipai, thank you for creating this package. Some questions I have before using it:
Do you consider this package a demo or is it supposed to be open source and used by the community?
Would you be willing to add a license?
Can you provide a rough timeline when this package will be production ready?
Which features are missing until you would consider releasing a v1.x?
I might also be able to contribute if you would be willing to accept help.

Thank you!

The configuration in 'pentatrion_vite.yaml' doesn't work with Docker

Hello

Thanks for your bundle.

I tried to use it with Docker, but I have some issue. To work with docker, I have to define a host in 'vite.config.js' :

export default defineConfig({
    plugins: [react(), symfonyPlugin()],
    build: {
        rollupOptions: {
            input: {
                app: "./assets/App.tsx",
            },
        },
    },
    server: {
        port: 3000,
        host: '0.0.0.0',
    },
});

But if I do that, the generated entrypoint.json don't work anymore, because the host will be now '0.0.0.0' instead of 'localhost

{
  "isProd": false,
  "viteServer": {
    "origin": "http://0.0.0.0:3000",
    "base": "/build/"
  },
  "entryPoints": {
    "app": {
      "js": [
        "http://0.0.0.0:3000/build/assets/App.tsx"
      ]
    }
  },
  "assets": null
}

I tried to add this in config/packages/pentatrion_vite.yaml

pentatrion_vite:
    server:
        host: localhost
        port: 3000
        https: false

But it didn't work

The only solution I found is to add 'origin: 'http://localhost:3000' in Vite config

export default defineConfig({
    plugins: [react(), symfonyPlugin()],
    build: {
        rollupOptions: {
            input: {
                app: "./assets/App.tsx",
            },
        },
    },
    server: {
        origin: 'http://localhost:3000',
        port: 3000,
        host: '0.0.0.0',
    },
});

And I removed the pentatrion_vite.yaml (this file didn't work)

Now, the entrypoints.json is OK, and everything is working fine with Docker.

I spend a lot of time to figure why this bundle didn't work with Docker, so if this issue can help someone else who struggle to use this bundle with docker.

βœ… [Question] CORS error when using HTTPS

Hi,

I am new to using Vite.js and your bundle, and I’ve just tried loading an example, which works using HTTP for the Vite dev server, except that I get unwanted page reloads.

To serve my Symfony website project, I am not using the Symfony local server, but Apache, with HTTPS because I needed it for some features.

Since you say in your README that we should use the same HTTP or HTTPS protocol for both, I enabled https like you explain, but when I do that, my page can’t load resources from the Vite dev server anymore. This is what is shown in the Firefox console :

Blocage d’une requΓͺte multiorigine (Cross-Origin Request) : la politique Β« Same Origin Β» ne permet pas de consulter la ressource distante situΓ©e sur https://localhost:3000/build/@vite/client. Raison : Γ©chec de la requΓͺte CORS. Code d’état : (null).
L’URI de la source du module n’est pas autorisΓ© dans ce document : Β« https://localhost:3000/build/@vite/client Β».
Blocage d’une requΓͺte multiorigine (Cross-Origin Request) : la politique Β« Same Origin Β» ne permet pas de consulter la ressource distante situΓ©e sur https://localhost:3000/build/js/ol6_example.js. Raison : Γ©chec de la requΓͺte CORS. Code d’état : (null).
L’URI de la source du module n’est pas autorisΓ© dans ce document : Β« https://localhost:3000/build/js/ol6_example.js Β».

ol6_example.js is the module I am including in my Symfony template with {{ vite_entry_script_tags('js/ol6_example.js') }}

In my vite.config.js file, I tried setting server.cors, but the Vite.js documentation states that any origin is already allowed by default, so I didn’t expect it to change anything.

export default defineConfig({
    server: {
        https: true,
        cors: true,
    //...

Do you have an idea how can I fix this problem? Thank you

TypeError: symfonyPlugin is not a function when building as module

In order to use Svelte with Typescript and SCSS, I added svelte.config.js in the root of my project containing

import sveltePreprocess from 'svelte-preprocess'

export default {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
  preprocess: sveltePreprocess()
}

However, this leads to an error

import sveltePreprocess from 'svelte-preprocess'
^^^^^^

SyntaxError: Cannot use import statement outside a module

Indeed, a bare Svelte / Typescript / Vite project has

    "type": "module"

in package.json.

However, now npm run dev complains that

failed to load config from /Users/marcel/Sites/project/vite.config.js
error when starting dev server:
TypeError: symfonyPlugin is not a function

My complete vite.config.js contains this:

import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";
import {svelte} from "@sveltejs/vite-plugin-svelte";

export default defineConfig({
    plugins: [
        svelte(),
        symfonyPlugin()
    ],
    root: ".",
    base: "/build/",
    build: {
        manifest: true,
        emptyOutDir: true,
        assetsDir: "",
        outDir: "./public/build",
        rollupOptions: {
            input: {
                app: "./assets/main.ts"
            },
        },
    },
});

My package.json currently has

{
    "private": true,
    "type": "module",
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "license": "UNLICENSED",
    "devDependencies": {
        "@sveltejs/vite-plugin-svelte": "^1.0.0-next.40",
        "@tsconfig/svelte": "^3.0.0",
        "svelte": "^3.46.6",
        "svelte-check": "^2.4.6",
        "svelte-preprocess": "^4.10.5",
        "tslib": "^2.3.1",
        "typescript": "^4.6.3",
        "vite": "~2.8",
        "vite-plugin-symfony": "^0.3.0"
    },
    "dependencies": {
    }
}

Cannot access offset of type string on string

I just updated the bundle from v3.3.1 to v4.0.2 on my project with composer require 'pentatrion/vite-bundle:^4.0'. But now I get the following error:

image

I reduced my vite config to the bare minimum:

import { defineConfig } from "vite"
import symfonyPlugin from "vite-plugin-symfony"
import react from "@vitejs/plugin-react"
import { fileURLToPath, URL } from "node:url"

export default defineConfig({
	plugins: [react(), symfonyPlugin()],
	build: {
		rollupOptions: {
			input: {
				"generation-add": "./assets/js/pages/generation/add/index.tsx",
			},
		},
	},
	server: {
		origin: "http://localhost:3000",
		port: 3000,
		host: "0.0.0.0",
	},
	resolve: {
		alias: {
			app: fileURLToPath(new URL("./assets/js", import.meta.url)),
		},
	},
})

Here is how I call the vite_entry_link_tags and vite_entry_script_tags functions (templates/base.html.twig file):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="initial-scale=1, width=device-width" />
        {% block stylesheets %}
          {{ vite_entry_link_tags("generation-add") }}
        {% endblock %}

        {% block javascripts %}
            <script type="text/javascript">
                window.pageProps = {{ (pageProps ?? '{}')|raw }};
            </script>
            {{ vite_entry_script_tags("generation-add", { dependency: "react" }) }}
        {% endblock %}
    </head>
    <body>
        {% block body %}<div id="app"></div>{% endblock %}
    </body>
</html>

I also tried v4.0.1 and v4.0.0 and still got the same issue. v3.3.1 works fine. Did I do something wrong on the upgrade process? Is there any upgrade guide?

Integrity hash generated on a different file than the one built

Hey, it's me again ! 😬

Thanks again for your work.

I implemented, in my company app, your new SRI Feature and i am facing an error :

Failed to find a valid digest in the 'integrity' attribute for resource 'example.js' with computed SHA-384 integrity 'FFnZ[...]'. The resource has been blocked.

So i tried to locally generate a hash for my example.js, and it does not match the one generated in the entrypoints.json (but it matches the integrity hash given by my browser, shared in the error message).

After some few investigations, it looks like the chunk example.js given to the generateHash() in vite-plugin-symfony isn't exactly the same as the example.js built in my build folder. The one given has some __VITE_PRELOAD__ inside his code near where i do some lazy imports with React.

If you need some more informations please let me know.

Have a great day !

Pentatrion\ViteBundle\Asset\EntrypointsLookup::getLegacyJSFile(): Return value must be of type string, array returned

Hello,
I get this error with @vitejs/plugin-legacy.

It seems that the target value is an array with keys path and hash.
image

vite: 4.4.9
@vitejs/plugin-legacy: 4.1.1

import {defineConfig, splitVendorChunkPlugin} from 'vite'
import vue from '@vitejs/plugin-vue'
import symfonyPlugin from "vite-plugin-symfony";
import {resolve} from 'path';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
        plugins: [
            vue(),
            splitVendorChunkPlugin(),
            VueI18nPlugin({
                strictMessage: false,
                include: resolve(__dirname, 'assets/locales/*.json'),
                jitCompilation: false,
            }),
            legacy({
                targets: ['defaults', 'not IE 11'],
            }),
            symfonyPlugin(),
        ],
        build: {
            target: 'es2020',
            manifest: true,
            rollupOptions: {
                input: {
                    app: './assets/app.ts',
             
                },
                output: {
                  chunkFileNames: "assets/[hash:15].js"
                },
            },
            outDir: "public/build",
        },
        resolve: {
            alias: {
                '~': resolve(__dirname, 'assets'),
                'vue': 'vue/dist/vue.esm-bundler.js',
            },
            extensions: ['.js', '.ts', '.vue', '.json']
        }
    }
)

Am i missing something ?

Error `Entry points must be inside Vite root directory`

vite.config.js

import { defineConfig } from 'vite';
import symfony from 'vite-plugin-symfony';

export default defineConfig(async ({ mode }) => {
    return {
        publicDir: './public/',
        base: '/static/',
        build: {
            outDir: './public/static/',
            manifest: true,
            emptyOutDir: true,
            copyPublicDir: false,
            rollupOptions: {
                input: 'assets/main.ts',
            },
        },
        plugins: [
            symfony.default(),
        ],
    };
});

Running vite build starts building but stops intermediately with this message:

rendering chunks (73)...Entry points must be inside Vite root directory

options for vite_entry_link_tags / vite_entry_script_tags

SalΓ»t,

both script and link elements support various attributes to improve load and execution order and as a result have an impact on page performance.
These attributes include link prefetch, preload or script defer, async, type, nomodule etc.

Are there ways to set additional attributes to individual vite_entry_link_tags() and vite_entry_script_tags() calls so one can control how certains scripts and stylesheets are downloaded by the browser?

I only found $options['dependency'] in renderScripts apparently dealing with React and no options whatsoever for renderLinks

Thank you.


Harry Roberts (aka csswizardry) explains this in his talk "Get your head straight".

"Get your head straight" by Harry Roberts, Web Performance Engineer

Vite HMR and symfony serve

SalΓ»t,

we currently use Symfony Encore in several projects, one is planned for relaunch using Vue3 and I was hoping to move away from Encore and WebPack and use Vite with this fine bundle.

To get more familiar with this, I have created a blank local symfony test project using the symfony binary. All things like Twig, loading the "app" js and css etc. works fine, but I can't get HMR to work.

symfony server:start --no-tls or symfony serve --no-tls run on http://127.0.0.1:8000/ where I can see the output of my routes and twig templates.
I need to run build --watch instead of dev, then manually refresh the browser to see the change.
Using build seems ok with a couple of scripts, but there will be loads more js and css files in the actual web project. I have no experience yet whether build watch mode will give us the same DX like dev watch mode, let alone build doesn't give me HMR, which is one major selling point for using Vite in the first place.

When I run yarn dev --watch, Vite tells me to visit Local: http://127.0.0.1:5173/build/ where all I find is the Symfony + Vite default page
image
This is not the place to view your application. To access your Symfony application, you will need to run a local development server. symfony serve

What's this /build route for?
How does symfony serve with yarn dev (vite) give me hot module reloads?

I understand port 5173 is Vite's new default port, but how do I "link" this with Symfony's local web server ...
... or eventually nginx which is used for developing the final website and running on a different machine. Would this then require port forwarding?

I'm a bit lost here and any help and hints are appreciated. πŸ™

Thank you!

Update react usage

The correct way to use react and to get HMR / Fast refresh to works correctly is now to use @vitejs/plugin-react.
The configuration is almost the same:

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import symfonyPlugin from 'vite-plugin-symfony';

/* if you're using React */

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

Public services for easy DI

Hello, would you mind adding your services such as that I can DI them in __constuct() instead of using painful aliases ?

Following code does not work, because you can't reference classes and I have to add special entry in config/services

public function __construct(private EntrypointsLookup $entrypointsLookup)
{
}

image

Symfony/asset v4.4 Support

Hi,

When I was attempting to install this package, I came across this error:

PHP Fatal error:  Declaration of Pentatrion\ViteBundle\Asset\ViteAssetVersionStrategy::getVersion(string $path): string must be compatible with Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface::getVersion($path) in /var/www/vendor/pentatrion/vite-bundle/src/Asset/ViteAssetVersionStrategy.php on line 46

In ViteAssetVersionStrategy.php line 46:
                                                                               
  Compile Error: Declaration of Pentatrion\ViteBundle\Asset\ViteAssetVersionS  
  trategy::getVersion(string $path): string must be compatible with Symfony\C  
  omponent\Asset\VersionStrategy\VersionStrategyInterface::getVersion($path) 

This appears to be because the version of symfony/asset (4.4) I have installed has some slight type differences as can be seen here https://github.com/symfony/asset/blob/4.4/VersionStrategy/VersionStrategyInterface.php.

Are there any plans for supporting symfony/asset 4.4?

Many thanks!

Files only included in Dev-Mode

I've installed the bundle exactly as described in the README. The only change I've made is in vite.config.js, where I've imported the Vue plugin:

...
import vuePlugin from "@vitejs/plugin-vue";
...
  plugins: [
    vuePlugin(),
    symfonyPlugin,
  ],
...

When I run yarn dev, everything works as expected: The Vite server is started and the files get included.
But after running yarn build, the files get not included. The vite_entry_link_tags and vite_entry_script_tags return nothing.

Is there anything else to do?

Images fail to load in dev mode

I am importing and using an image like this:

import logo from "./logo.png"

const img = document.createElement("img")
img.src = logo
document.body.append(img)

When running npm run dev, the logo variable contains /build/js/components/logo.png. The browser tries to load the file but fails with a 404 error.

When I look in public/build, I have the output of a previous build, but no js/components/logo.png file.

If I run npm run build, there is works fine.

Here is my configuration file (vite.config.ts):

import { resolve } from "path"
import { unlinkSync, existsSync } from "fs"
import react, { Options } from "@vitejs/plugin-react"
import glob from "glob"
import { defineConfig } from "vite"

const symfonyPlugin = {
  name: "symfony",
  configResolved(config: any) {
    if (config.env.DEV && config.build.manifest) {
      let buildDir = resolve(config.root, config.build.outDir, "manifest.json")
      existsSync(buildDir) && unlinkSync(buildDir)
    }
  },
  configureServer(devServer: any) {
    let { watcher, ws } = devServer
    watcher.add(resolve("templates/**/*.twig"))
    watcher.on("change", function (path: string) {
      if (path.endsWith(".twig")) {
        ws.send({
          type: "full-reload",
        })
      }
    })
  },
}

const getEntrypoints = () => {
  return glob.sync("./assets/js/pages/**/index.tsx")
}

export default defineConfig({
  plugins: [react({ configFile: true } as Options), symfonyPlugin],
  server: {
    watch: {
      disableGlobbing: false,
    },
    fs: {
      strict: false,
      allow: [".."],
    },
  },
  root: "./assets",
  base: "/build/",
  build: {
    manifest: true,
    emptyOutDir: true,
    assetsDir: "",
    outDir: "../public/build/",
    rollupOptions: {
      input: getEntrypoints(),
    },
  },
  resolve: {
    alias: {
      app: resolve(__dirname, "assets/js"),
    },
  },
  optimizeDeps: {
    include: ["react", "react-dom", "@mui/material"],
  },
})

Outputting a single file per entrypoint doesn't work

I would like to have one js file per entrypoint (input) in my final build, as per https://symfony-vite.pentatrion.com/guide/tips.html#one-file-by-entry-point I should set manualChunks to undefined but that didn't work for me on vite 4.0 and symfony 6.3, I see many js files being imported as before.

Vite config:

import { defineConfig } from 'vite';
import symfonyPlugin from 'vite-plugin-symfony';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import checker from 'vite-plugin-checker';
import elmPlugin from 'vite-plugin-elm';

export default defineConfig({
    plugins: [
        checker({
            // e.g. use TypeScript check
            typescript: true,
            // eslint: true
        }),
        elmPlugin(),
        react(),
        symfonyPlugin(),
        tsconfigPaths(),
    ],
    publicDir: false,
    base: '/build',
    build: {
        outDir: '../public/build',
        assetsDir: './',
        emptyOutDir: true,
        sourcemap: true,
        rollupOptions: {
            input: {
             // multiple inputs here
              app1: './App1/index.ts',
              app2: './App2/index.ts'
            },
            output: {
              manualChunks: undefined,
            },
        },
    },
});

I would like to just see everything bundled up in app1.js, app2.js

Related issues:
vitejs/vite#12203

Maybe it relates to an upstream issue in rollup which vite uses internally for bundling:
rollup/rollup#2756

Provide a solution for "vite-plugin-react can't detect preamble. Something is wrong."

Thanks for writing this bundle!

I'm trying to use it with React but this error occurred when using dev server.

As what discussed in vitejs/vite#1984,
it seems that Vite cannot inject a piece of code used for React hot reloading,
since the HTML is generated by PHP.

After adding these code in Twig template, things worked.

        {% block javascripts %}
            <script type="module">
                import RefreshRuntime from "/build/@react-refresh"
                RefreshRuntime.injectIntoGlobalHook(window)
                window.$RefreshReg$ = () => {}
                window.$RefreshSig$ = () => (type) => type
                window.__vite_plugin_react_preamble_installed__ = true
            </script>
            {{ vite_entry_script_tags('app') }}
        {% endblock %}

The code coming from: https://github.com/vitejs/vite/blob/d9f6dc0ecfc0f6a1c394c8645f474cb32a9e447a/packages/plugin-react/src/fast-refresh.ts#L31-L37

Should we provide a solution for this issue (not a bug of Vite though) out-of-the-box? That would help many React developers.

Thanks!

Images in SASS is not resolved in dev mode

In the scss file I have a url with the path to the image, which vite translates correctly. The problem is that it forgets to add the base url from vite dev mode.

.logo {
	background-image: url(/assets/images/logo.svg);
}

In browser console is:
image

But for me, the url has to be this: https://localhost:5173/build/assets/images/logo.svg

Am I doing something wrong? Am I configured it wrong?

Thanks for your help.

Question about integrating vite plugin checker

I want to integrate https://vite-plugin-checker.netlify.app/ to check typescript errors actively while the dev server is running, by default this plugin shows errors in both terminal and web ui but for traditional back-ends like symfony an additional file needs to be included:

https://vite-plugin-checker.netlify.app/faq/integration.html#overlay-does-not-display-in-development-mode

Is their a way to auto inject this file where-ever we use vite_entry_script_tags?

How to configure for more than one Vite app?

Hello,

The provided config works if there's just one Vite app in the project. However, I would like to have more apps.

How can I provide multiple build directories with corresponding public paths? Thanks.

pentatrion_vite:
  # Base public path when served in development or production
  base: /build/

Handle multiple builds

Hi!

First of all, thanks for your work and for that very useful bundle!

With my team, we currently are trying to migrate all our Symfony bases apps from webpack encore to vite, but there is one final point that prevent us from migrating all of them. It's about handling multiple builds in separate build directories, with a manifest.json/entrypoints.json for each one.

Currently, symfony/webpack-encore-bundle provides a solution with this configuration:

webpack_encore:
    # if you have multiple builds:
    builds:
        frontend: '%kernel.project_dir%/public/frontend/build'

Used with this twig:

{{ encore_entry_script_tags('app', null, 'frontend') }}

Are there any plans about adding this feature to your bundle, or have you ever thought about that?

Would also be interesting to know if you are looking to provide the "exact" same features as in symfony/webpack-encore or if you just aim to provide a way to use Vite in some SF apps.

Enable Discussions

SalΓ»t @lhapaipai ,

would you mind to enabled "Discussions" for both this repo and the Vite plugin?
Then users of this package could exchange ideas, help each other, and talk about possible extensions, settings, tweaks ...

I believe to be on par with Symfony Encore, a few small things are still missing that may however not necessarily require creating a new issue.

Thank you!

Conditional imports generate modulepreloads for everything

The vite_entry_script_tags twig function adds modulepreload links for conditional imports (if (condition) { import('some-module.ts'); }).
This should probably not happen, since the whole point of conditional imports is to avoid loading the resource at all when it's not needed.

Apply a baseUrl to files from manifest?

Hi,

Currently, we cannot have a baseUrl applied to files from manfiest. Only base is prepended :

return $this->build['base'].$this->manifestData[$path]['file'];

My use case is simple : a Symfony application hosted in a subfolder.

  • assets paths would be standard : /public/build/assets/
  • assets urls : mydomain.com/subfolder/build/assets/

I know, it is possible to customize the vite build.outDir option to reflect my URL subfolder to my public dir, but it forces me to customize my reverse proxy to not apply any rewrite. It doesn't look elegant to me.

Am I missing something? What do you think about it?

Asset versioning with other bundles not working

When using the ViteAssetVersionStrategy it will resolve the "wrong" host url in dev environments when using other bundles in dev environment.
I was trying to install Nelmio/ApiDocBundle which loads static assets from public/bundles/nelmioapidoc but the ViteAssetVersionStrategy resolves the path to 127.0.1:3000/build/bundles/nelmioapidoc ($origin . $host . $path).

The problem comes from ViteAssetVersionStrategy::getassetsPath#L79-85

if (false !== $this->manifestData) {
            if (isset($this->manifestData[$path])) {
                return $this->build['base'].$this->manifestData[$path]['file'];
            }
        } else {
            return $this->entrypointsData['viteServer']['origin'].$this->entrypointsData['viteServer']['base'].$path;
        }

As a workaround I had to implement my own version strategy using the following class:

<?php

namespace App\Asset;

use Pentatrion\ViteBundle\Asset\ViteAssetVersionStrategy;

class CustomAssetVersionStrategy extends ViteAssetVersionStrategy
{

    public function getVersion(string $path): string
    {
        if (str_starts_with($path, "bundles")) return $path;

        return parent::getVersion($path);
    }

    public function applyVersion(string $path): string
    {
        if (str_starts_with($path, "bundles")) return $path;
        return parent::applyVersion($path);
    }

}

Bundle config being seemingly ignored

Server options seems to be ignored as setting host to a different domain other than localhost does nothing.

Then browser keeps reloading because it can't connect to the websocket.

[vite] connecting...
​ WebSocket connection to 'ws://my.domain.local:3000/build/' failed: 
(anonymous) @ client:188
​ [vite] server connection lost. polling for restart...
 GET http://my.domain.local/build/__vite_ping 404 (Not Found)

My config at config/packages/pentatrion_vite.yaml

pentatrion_vite:
    base: /build/
    public_dir: /public
    server:
        host: my.domain.local
        port: 3000
        https: false

Running the vite command shows that it's still listening to localhost.

vite v2.8.6 dev server running at:

  > Local: http://localhost:3000/build/
  > Network: use `--host` to expose

  ready in 12137ms.

Oddly enough, after upgrading vite from 2.7 to 2.8 and your plugin from 0.2.4 to 0.3.1 makes it that the server is suddenly slow as snail. It went from ready in about 1s to ready in 12 secs That is insane, any tips ? Is it scanning the whole project because the root is no longer ./assets but . in vite.config.js ?

import {defineConfig} from "vite"
import symfonyPlugin from "vite-plugin-symfony"
import { svelte } from "@sveltejs/vite-plugin-svelte"
import autoPreprocess from 'svelte-preprocess'
import viteDefineEnvs from "vite-define-envs-plugin"
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
    plugins: [
        symfonyPlugin(),
        svelte({
            preprocess: autoPreprocess()
        }),
        viteDefineEnvs(["NODE_ENV"], "process.env"),
        // visualizer({
        //     template: 'treemap',
        //     gzipSize: true,
        //     open: true,
        // })
    ],
    root: ".",
    base: "/build/",
    build: {
        manifest: true,
        emptyOutDir: true,
        assetsDir: "",
        outDir: "./public/build/",
        rollupOptions: {
            input: {
                app: "./assets/app.ts",
                admin: "./assets/admin.ts",
            },
        },
    },
    resolve: {
        alias: [
            {
                find: /^~.+/,
                replacement: (val) => {
                    return val.replace(/^~/, "");
                },
            },
        ],
    },
});

vite-plugin-symfony: 0.3.1
pentatrion/vite-bundle: 1.2.0

Configuration Option Base Ignored

I am trying to use this bundle in a Sulu CMS project. In order to do so and not overwrite the admin assets (that are built in /public/build/admin) I am trying to set the pentatrion_vite.base option to "/build/website".

If I run bin/console debug:container vite --show-arguments and select vite.entrypoints_lookup I get the appropriate path /public/build/website/entrypoints.json, however the generated html from the {{ vite_entry_link_tags('app') }} (and script tag) shows the default /public/build/ paths (no /website).

This seems to be the case even if changing build to something like app (so it is not to do with being a subdirectory).

Vite itself is placing the files in the correct place, so I believe the vite-plugin-symfony config is working correctly (pasted relevant option below for reference):

symfonyPlugin({
    buildDirectory: "/build/website/"
}),

Thank you & Symfony Slack

Thank you for writing this bundle - it works really well and I'm enjoying migrating my Symfony sites to Vite πŸ˜„

I wanted to let you know I've created a #vitejs channel on the Symfony Slack as there's starting to be regular questions about using Vite. I'll try and help people if they get stuck, and you'd be very welcome if you want to join Slack.

My assets are not linked in my twig files in production

Hey, thanks for your great work. I am currently migrating my app from Webpack-encore to Vite.

My app is using React & Symfony. I followed your instructions, and everything is working perfectly fine in dev server/locally, but i have issues when i am pushing to production in my Review App.

My twig are rendered without any <script> or <link> from my vite_entry_..._tag. I have no idea if that's because it can't find any assets so it doesn't write tags, or if that's because another reason.

My assets are btw uploaded in a CDN, so that's why i am using an env variable.

Do you have any ideas how can i fix that ? Thank you.

Here is my vite.config.js :

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());

  return {
    resolve: {
      alias: {
        // ...
      },
    },
    plugins: [
      react(),
      symfonyPlugin({
        /* defaultValues */
        servePublic: true,
        refresh: true,
        /** If you set server.host: '0.0.0.0' in your vite.config.js
         * you have to set 'localhost' */
        viteDevServerHostname: null,
      }),
    ],
    base: `${env.VITE_ASSET_PATH}/build`,
    build: {
      outDir: './public/build',
      manifest: true,
      rollupOptions: {
        input: {
          // ...
        },
      },
    },
    server: {
      origin: 'http://localhost:5173',
    },
  };
});

My entrypoints.json look like this :

  "entryPoints": {
    "example": {
      "js": [
        "https://cdn.example.com/build/assets/example-b5917c32.js"
      ],
      "css": [],
      "preload": [
        "https://cdn.example.com/build/assets/example-c72ab971.js",

My manifest.json :

  "Example.css": {
    "file": "assets/Example-09455f0e.css",
    "src": "Example.css"
  },

My pentatrion_vite.yaml :

# config/packages/pentatrion_vite.yaml
pentatrion_vite:
  # path to the web root relative to the Symfony project root directory
  public_dir: /public

  # Base public path when served in development or production
  base: /build/

My assets.yaml :

framework:
  assets:
    base_urls:
      - '%env(ASSET_PATH)%'
    json_manifest_path: '%kernel.project_dir%/public/build/manifest.json'

EDIT :
"Partially" fixed by changing "build" by an another name, somehow it was getting replaced by something.

Allow to reset EntrypointRenderer' state

Hello,

Thanks for this great bundle!

We've a specific use case where we render several times the same twig template in a service (pdf/screenshotting purpose).

Actually, you track the returnedViteClients and the returnedReactRefresh to avoid double loading and it's a good idea.

However when we try to render twice the same twig in a dedicated service, the second one doesn't have the vite client and the react refresh included, so the page is just blank 😁

image

I'll prepare a pull request to allow to reset the current state.

Thanks

Images not copied on build

Hello, I have a strange problem, some images are not copied in the directory public/build/ and the manifest is not correctly filled.
Some images are well added to the manifest and other images are not added at all.
I use the same method to load images (via {{ asset() }})

My config:

# config/packages/framework.yaml

framework:
  assets:
    version_strategy: 'Pentatrion\ViteBundle\Asset\ViteAssetVersionStrategy'
// vite.config.js

import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";

export default defineConfig({
    plugins: [
        symfonyPlugin(),
    ],
    build: {
        rollupOptions: {
            input: {
                app: "./assets/js/app.js",
            },
        }
    },
});
// assets/js/app.js

import.meta.glob(["../img/**"]);

In my base.html.twig

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

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

in my templates

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

it's a strange behavior =/

Edit: In dev mode, everything is ok

Upgrade to vite 2.8.x shows Entry points must be inside Vite root directory

Hey there!

unfortunately i cannot upgrade to vite 2.8. with the plugin.

When I downgrade vite to 2.7.x it works as before.

My vite config looks exactly like the readme.md file

I get the error: "Entry points must be inside Vite root directory"
i debugged a bit and it resolves the relative path wrong. It resolves it to the pwd instead of pwd + config.root, that's why the error occurs

Include publicDir: false in vite.config.js

When building a project for deployment I run npm run build, which runs vite build. By default, Vite will copy all assets in /public to the build directory. However, this is generally not what you want with the Symfony /public directory: apart from useless files like index.php it will also copy bundles in /public/bundles, so a directory is created. At this moment, you will run into trouble with npm run dev, which outputs:

error when starting dev server:
SystemError [ERR_FS_EISDIR]: Path is a directory: rm returned EISDIR (is a directory) /Users/xxx/Sites/project-dir/public/build/bundles

You can circumvent this whole copying behaviour by adding

publicDir: false

to vite.config.js.

Would this be a sane default to add to the README?

Error on run "pnpm dev"

Hi, i have some troubles with embeded configuration of vite

I'd like to use :

  • typescript
  • Sass & postcss with some plugins
  • imagein plugins
  • eslint & styelint

This is my pakage.json

{
    "private": true,
    "version": "0.0.0",
    "type": "module",
    "scripts": {
        "stylelint": "stylelint 'assets/**/*.{css,scss}' --fix",
        "eslint": "eslint --fix 'assets/**/*.{js,ts}'",
        "dev": "vite",
        "build": "tsc && vite build",
        "lint": "npm-run-all stylelint eslint",
    },
    "license": "UNLICENSED",
    "devDependencies": {
        "vite": "^4.0",
        "vite-plugin-symfony": "^0.7.2",
        "vite-plugin-favicon": "^1.0.8",
        "@types/eslint": "^8.4.10",
        "@typescript-eslint/eslint-plugin": "^5.48.2",
        "@typescript-eslint/parser": "^5.48.2",
        "@vheemstra/imagemin-avifenc": "^2.1.0",
        "@vheemstra/vite-plugin-imagemin": "^1.0.8",
        "autoprefixer": "^10.4.13",
        "cssnano": "^5.1.14",
        "cssnano-preset-default": "^5.2.13",
        "eslint": "^8.32.0",
        "eslint-config-standard": "^17.0.0",
        "imagemin": "^8.0.1",
        "imagemin-mozjpeg": "^10.0.0",
        "imagemin-pngquant": "^9.0.2",
        "imagemin-svgo": "^10.0.1",
        "imagemin-webp": "^8.0.0",
        "npm-run-all": "^4.1.5",
        "postcss": "^8.4.21",
        "postcss-combine-duplicated-selectors": "^10.0.3",
        "postcss-combine-media-query": "^1.0.1",
        "postcss-flexbugs-fixes": "^5.0.2",
        "postcss-sort-media-queries": "^4.3.0",
        "sass": "^1.57.1",
        "stylelint": "^14.16.1",
        "stylelint-config-standard": "^29.0.0",
        "stylelint-config-standard-scss": "^6.1.0",
        "stylelint-scss": "^4.3.0",
        "typescript": "^4.9.3"
    }
}

this is my "tsconfig.json"

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": false,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true,
    "types": ["vite/client"],
  },
  "include": ["assets"]
}

this is my "pentatrion_vite.yaml"

# config/packages/pentatrion_vite.yaml
pentatrion_vite:
  # path to the web root relative to the Symfony project root directory
  public_dir: /public

  # Base public path when served in development or production
  base: /assets

  script_attributes:
  # you can define your attributes that you want to apply
  # for all your script tags

  link_attributes:
  # you can define your attributes that you want to apply
  # for all your link tags

An finally, this is my "vite.config.js" :

import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";

//import { resolve } from 'path';
import viteImagemin from '@vheemstra/vite-plugin-imagemin';
import { ViteFaviconsPlugin } from "vite-plugin-favicon";
import autoprefixer from 'autoprefixer';
import combineSelectors from 'postcss-combine-duplicated-selectors';
// @ts-ignore
import combineMediaQueries from 'postcss-combine-media-query';
// @ts-ignore
import postcssSortMediaQueries from 'postcss-sort-media-queries';
// @ts-ignore
import postcssFlexbugsFixes from 'postcss-flexbugs-fixes';
import cssnano from 'cssnano';

import imageminMozjpeg from 'imagemin-mozjpeg';
import imageminWebp from 'imagemin-webp';
import imageminPngQuant from 'imagemin-pngquant';
import imageminSvgo from 'imagemin-svgo';


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

const isProd = process.env.NODE_ENV === 'production';

export default defineConfig({
    server: {
        open: false,
        port: 19875,
    },
    base: './',
    root: '',
    css: {
        postcss: {
            plugins: [
                postcssFlexbugsFixes({ bug6: false }),
                postcssSortMediaQueries( {sort: 'mobile-first',
                    configuration: {
                        unitlessMqAlwaysFirst: true,
                    }}),
                autoprefixer(),
                combineMediaQueries(),
                combineSelectors({ removeDuplicatedValues: true }),
                cssnano( {
                    preset: 'cssnano-preset-default'
                }),
            ],
        },
    },
    build: {
        outDir: 'public',
        emptyOutDir: true,
        rollupOptions: {
            input: {
                // main: resolve(__dirname, '', 'index.html'),
                app: "./assets/scripts/main.ts",
                "home": "./assets/styles/scss/home.scss",
            },
        },
        minify: isProd,
    },
    plugins: [
        ViteFaviconsPlugin({
            logo: './assets/icons/favicon.svg',
            inject: false,
        }),
        viteImagemin({
            plugins: {
                jpg: imageminMozjpeg({quality: 75}),
                png: imageminPngQuant({quality: [0.65, 0.9], speed: 4}),
                svg: imageminSvgo({
                    plugins: [
                        {name: 'removeTitle', active: true},
                        {name: 'removeComments', active: true},
                        {name: 'removeDesc', active: true},
                        {name: 'removeViewBox', active: false},
                        {name: 'removeDimensions', active: true},
                        {name: 'removeScriptElement', active: true},
                        {name: 'removeStyleElement', active: true},
                        {name: 'removeEmptyAttrs', active: false},
                    ],
                }),
            },
            makeWebp: {
                plugins: {
                    jpg:imageminWebp(),
                    png:imageminWebp(),
                },
            },
        }),
        /* react(), // if you're using React */
        symfonyPlugin({
            servePublic: true,
            publicDirectory: 'public',
            buildDirectory: 'public',
        }),
    ],
})

The problem is when i run "pnpm dev" i have an error

failed to load config from H:\my-project\server\vite.config.js
error when starting dev server:
TypeError: symfonyPlugin is not a function

I tried to rename "vite.config.js" to "vite.config.ts" but same error

If i comment "symfonyPlugin" in vitejs.config plugin section. Vite server is launched without error. But, of course my assets are not served throught Symfony

An exception has been thrown during the rendering of a template ("assets entrypoints file "H:\my-project\server/public/assets/manifest.json" does not exist. Did you forget configure your base in pentatrion_vite.yml?").

This vitejs config work well, i'm using it when i'm create my html pages as static (without the symfonyPlugin of course)

Do you have a clue on how to solve this error ?

Best regards
Jerome

nonce attribute missing

{{ vite_entry_script_tags( 'app', { attr: { nonce: 'my-nonce'} }) }}

This adds a nonce, but only to app.js script:

<script src="https://127.0.0.1:5173/build/@vite/client" **nonce is expected here** type="module"></script>
<script src="https://127.0.0.1:5173/build/assets/app.js" nonce="" type="module"></script>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.