etherCorps / sveltekit-og

Generate Open Graph Images dynamically from HTML/CSS without a browser in SvelteKit
https://sveltekit-og.ethercorps.io/
200 stars 12 forks source link

add docs re: build.rollupOptions.external when using adapter-node? #44

Open aaronjbecker opened 6 months ago

aaronjbecker commented 6 months ago

I finally got sveltekit-og working under adapter-node inside a container but it was kind of painful because of the way that sveltekit/vite/rollup deal with non-code dependencies like binaries and JSON. First I encountered an issue with resvg bundling, then an issue with svelte/compiler and css-tree. I solved both issues using the same approach. First install into (non-dev) dependencies like so:

    "dependencies": {
        "@ethercorps/sveltekit-og": "^3.0.0",
        "@resvg/resvg-js": "^2.6.0",
        "css-tree": "^2.3.1"
    }

and then mark css-tree and @resvg/resvg-js as external in vite.config.js:

export default defineConfig({
     ...
    build: {
        rollupOptions: {
            // cf. https://rollupjs.org/configuration-options/#external
            external: ['@resvg/resvg-js', 'css-tree'],
        }
    }
});

This setup works for me when deployed using adapter-node inside a Docker container. I tried the css-tree-resolver custom vite plugin that @theetherGit suggested here, as well as the one packaged with sveltekit-og, but in both cases I still got import errors at runtime.

I am finding that the most reliable approach with external dependencies that include non-code artifacts, like JSON or .node binaries, is to avoid bundling the dependency altogether by including it in build.rollupOptions.external.

This only works if you only use these packages in +(page.)server.(js/ts) files and/or modules under $lib/server. But node binaries don't run in the browser anyway, and it practically speaking doesn't matter how much code you stuff into a docker container, so the upside for optimizing these dependencies is slight. I have found that it's less of a headache to just avoid bundling them altogether.

I can add this to the README, just wanted to run these thoughts by you first @etherCorps, maybe work up a minimal reproduction/example template on stackblitz, etc.

theetherGit commented 6 months ago

Thank you so much, I haven't tested this but it will be a good option to put it in docs. For vercel vite plugin works fine. This package is suppose to work for server only endpoints.