Skip to content

Instantly share code, notes, and snippets.

@assertchris
Last active February 8, 2023 14:11
Show Gist options
  • Save assertchris/96959e146097e0a3535315dd7832acdc to your computer and use it in GitHub Desktop.
Save assertchris/96959e146097e0a3535315dd7832acdc to your computer and use it in GitHub Desktop.

I'd like to share a complex Livewire + Alpine component I've made. I can piece together all the things I need to do to release it from a backend perspective. This includes things like an auto-discoverable service provider, custom Livewire component registration etc.

The difficulty I am having is that I want to write the JS for this component away from the view so that the view is easy to customise. Instead of x-data="{...}", I'd like to do soemthing like x-data="SearchTagField", and have all the gubbins of this Alpine component live in a JS file somewhere else.

I can't seem to find a good way to do this.

I think of what it must be like to ship this JS file with my library. To require the consumer to import '../../vendor/x/y/dist/Component' and I throw up a little in my mouth. I could tell the consumer what to customise in Webpack or Vite; but that's a lot of config to expect them to do and doesn't begin to cover the range of possible frontend build tools that they might want to use.

What if we had a way to register JS and CSS files that would be injected as part of <livewire:scripts /> and <livewire:styles />? Something like:

// in a service provider
function boot()
{
    Livewire::registerJS('path/to/custom/js');
    Livewire::registerCSS('path/to/custom/css');
}

Note: this would be something I do as part of the plugin's service provider. The goal is someone does a composer require and they can immediately use the <acme-component /> my library provides; without any frontend config.

@calebporzio
Copy link

Nice, thanks for this writeup Chris, I think this makes perfect sense. And then the contents of this path get auto-bundled into Livewire's JavaScript.

I'm not going to add this to V3 before launch, but I think this needs to be added shortly after. Also I don't want to enable this for V2.

After we launch V3, I'd love to see a PR (if we don't do something by that time)

@assertchris
Copy link
Author

Sounds good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment