ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Support bundling custom/addon CP assets with Vite

Open jacksleight opened this issue 3 years ago • 2 comments
trafficstars

It would be great if we could bundle custom/addon CP assets with Vite instead of Mix. I've taken a look at it and and got 90% of the way there, but there's a hiccup.

First add the cp.js file to vite.config.js:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
    plugins: [
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
            'resources/js/cp.js', // <---
        ]),
    ],
});

Then instead of this:

Statamic::script('app', 'cp.js');

Use this:

use Illuminate\Support\Facades\Vite;

Statamic::externalScript(Vite::asset('resources/js/cp.js'));

If you're just running vite build and then serving the built file from the manifest this works.

But, if you want to use the Vite server with automatic reloading etc. there are two problems:

1. type="module"

The script needs the type="module" attribute, and Statamic does not currently support adding that to the tag. This could be solved by supporting an array of additional attributes in the Statamic::script() and Statamic::externalScript() methods.

2. Async loading

By adding type="module" the script gets loaded asynchronously, which means Statamic.start() can end up running before the Statamic.booting/booted() calls, so the callbacks don't get executed. There might be a better way to solve this, but if Statamic.booting/booted() knew whether Statamic.start() had already been called they could just run the callback immediately? I know that kinda breaks the sequence, I guess it could cause issues depending on what you're doing in those callbacks.

jacksleight avatar Sep 30 '22 09:09 jacksleight

I was hacking on this yesterday too because of https://github.com/statamic/cms/discussions/6662

Got close and ran into the same sort of hurdles.

I'd say stick to webpack/mix for now, as changing how our script setup works is not really a priority. But of course we'd consider a PR.

jasonvarga avatar Sep 30 '22 13:09 jasonvarga

Cool. I may look at a PR at some point, but Mix is fine for now.

Yeah seems like the async issue is the trickiest problem.

jacksleight avatar Sep 30 '22 14:09 jacksleight