putyourlightson / craft-sprig

A reactive Twig component framework for Craft CMS.
https://putyourlightson.com/plugins/sprig
MIT License
129 stars 9 forks source link

docs: add explicit information for craft-vite usage #376

Closed mandrasch closed 3 months ago

mandrasch commented 5 months ago

Feature Request

Hey, thanks very much for providing Sprig as open source!

After we discussed on Discord, I thought it would be helpful to extend this section https://putyourlightson.com/plugins/sprig#htmx in the docs.

Proposed changes:

If you are a user of nystudio107/craft-vite, it is recommended to load htmx.org in your build.

{# Disable automatic registering and loading of the htmx script. #}
{% do sprig.setRegisterScript(false) %}

(# normal vite loading via nystudio107/craft-vite #}
{{ craft.vite.script("app.ts", false) }}

Add the htmx.org package with your preferred package manager, adjust the version number to the latest version used in Sprig (see Changelog).

npm install htmx.org@1.9.12
yarn add htmx.org@1.9.12
pnpm add htmx.org@1.9.12

In a file like app.ts, htmx can now be globally imported via:

import htmx from 'htmx.org';

Use it via

htmx.on('htmx:afterSwap', function () {

});

Haven't tried without TypeScript, but should be the same. Can test with vanilla-ks as well if it is helpful.

Plugin Version

3.0.2

bencroker commented 5 months ago

Rather than adding Vite specific docs, might it be worthwhile explaining how the script is registered, followed by providing an example of how to load it early? And can you please test whether this works for you?

{# Load the htmx script at the beginning of the body. #}
{% do sprig.setRegisterScript({ position: constant('craft\\web\\View::POS_BEGIN') }) %}

(# normal vite loading via nystudio107/craft-vite #}
{{ craft.vite.script("app.ts", false) }}
mandrasch commented 5 months ago

Mh ... that would mean I would lose the type support I get from import htmx from 'htmx.org';, because without it it would result in Cannot find name 'htmx'.. So at least in typescript importing would be my preferred way. Or am I missing something?

For Vanilla JS I could check if

{% do sprig.setRegisterScript({ position: constant('craft\\web\\View::POS_BEGIN') }) %}

works. 👍

bencroker commented 3 months ago

I reviewed the docs at https://putyourlightson.com/plugins/sprig#htmx and think they contain enough detail as is. I did provide more detail to sprig.setRegisterScript, however.