matthew-ia / cayo

A Svelte-powered static HTML generator for the small stuff, with islands of reactivity šŸ
MIT License
5 stars 0 forks source link

Docs: svelte-preprocess only operates on Markup #118

Open matthew-ia opened 1 year ago

matthew-ia commented 1 year ago

Maybe because of Cayo's order of internal processes, Svelte preprocess only operates on stuff that's in a source file if you were to read it as is.

E.g., replace in svelte-preprocess doesn't work on strings that are dynamically generated via some JS within the component.

Say I have a config for replace that is supposed to replace $assets$ with some/path/to/assets, and I have a component:

<!-- some.svelte -->
<script>
  const prependAssetPath = (src) => '$assets$/' + src;
</script>

<p>The assets are hosted at $assets$</p>
<img src={prependAssetPath('image.jpg')}>

The resulting HTML would be:

<p>The assets are hosted at some/path/to/assets</p>
<img src="$assets$/image.jpg">

But we'd expect both instances of $assets$ to have been replaced; we'd want <img src="some/path/to/assets/image.jpg">.

matthew-ia commented 1 year ago

Need to check if this is actually a Svelte bug / limitation. If that's the case, it sorta makes sense in terms of "preprocessing", which I'm pretty sure does indeed operate on the source files, not the resulting HTML of a component.

If Svelte is the problem, then we'll need to add cayo postprocess functionality, to at least just take functions as transformers that operate on the resulting code. OR, maybe Vite supports this exact thing via plugins and we could extend Cayo to support Vite plugins for this use case?

matthew-ia commented 1 year ago

Figured out that this is because svelte-preprocess only works on markup. The fix is either to use vite-plugin-replace, @rollup/plugin-replace, and/or write a custom preprocessor that preprocess both script and markup.

The Rollup plugin method doesn't work with conditional rendering for prerendered components, so you would need to write a custom preprocessor. Note: the custom preprocessors (for Svelte Preprocess API) will not affect external files, even if you are preprocessing <script>.

Closing this since it's not actually a bug with Cayo.

matthew-ia commented 1 year ago

Might be worth documenting this in Cayo's docs though, because no one else does a good job of it. (Had to create like 3 repro repos to figure out where the limitation was.)

matthew-ia commented 1 year ago

Reopened to track needing to add docs for this. Pretty much just need to have a brief section about preprocessors, if there isn't already one, that talks about svelte-preprocess being included, but only operating on markup. If you want something like a string replacement within CSS, you'll need to write your own processor or use an exisiting package (a preprocessorā€”I don't think a Rollup package touches the CSS either, as I think it's actually Vite and/or Svelte that handles the CSS output towards the end of the process).