sveltejs / kit

web development, streamlined
https://kit.svelte.dev
MIT License
17.81k stars 1.78k forks source link

hooks transformPageChunk html not replacing class #12150

Open shinokada opened 3 weeks ago

shinokada commented 3 weeks ago

Describe the bug

I have the following hooks.server.ts. It replaces all words starting and ending with underbar, _ with 'world'.

It works for all the texts but it doesn't work for class.

// hooks.server.ts
export async function handle({ event, resolve }) {
    const response = await resolve(event, {
        transformPageChunk: ({ html }) => {
            const regex = /\b_\w+?_\b/g;

            return html.replaceAll(regex, 'world');
        }
    });

    return response;
}

+page.svelte

<h1 class="_main_h1_">Hello "_main_h1_"</h1>

Output:

<h1 class="_main_h1_" data-svelte-h="svelte-310lox">Hello "world"</h1>

If it is intended so, how can I apply replaceAll() to class names?

Reproduction

I create a simple stackblitz.

https://stackblitz.com/edit/sveltejs-kit-template-default-3msgtk?file=src%2Froutes%2F%2Bpage.svelte

Logs

No response

System Info

// stackblitz
System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.18.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.3 - /usr/local/bin/pnpm
  npmPackages:
    svelte: ^4.2.7 => 4.2.15

Severity

annoyance

7nik commented 3 weeks ago

If you check what the server gives away, you'll see that both _main_h1_ are replaced. But, at hydration, it gets fixed to match the component template. You can also see it by adding export const csr = false; to the +page.js. Not sure why only the class gets fixed.

Such use of transformPageChunk doesn't seem to be correct, or at least good, because it causes a hydration mismatch, and such substitution cannot be done for pages rendered on the client.