evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
38.19k stars 1.15k forks source link

Question: splitting component logic from library code #3955

Open dennisfrijlink opened 2 weeks ago

dennisfrijlink commented 2 weeks ago

Maybe not the best place for a library-related question but I can't find something like a Discord server. Sorry for that.

I'm looking for a way to split component based logic from the base library/framework where the components is written in. So think of a Button and a Dropdown Component both written in Svelte. I try to find out a way to bundle and compile the code in to something like:

/build:
    - svelte.js (base svelte code. Not related to the logic of Button.svelte but necassary to make the component work.
    - button.js (compiled svelte code related to the button.svelte component. Needs svelte.js to be loaded to work)
    - dropdown.js (compiled svelte code related to the dropdown.svelte component. Needs svelte.js to be loaded to work)

My knowledge about code bundlers is a little bit limited so reading the docs of esbuild is sometimes hard.

Question: how to compile svelte components such that the base svelte code gets splitted of the specific component logic?

Thanks in advance!

hyrious commented 1 week ago

Svelte components (also Vue, React, etc.) are often distributed without (i.e. made external) svelte.

If your're a library author and want to publish a svelte component package, the ideal way is like:

// package.json
{
  "svelte": "./lib/Button.svelte", // points to the source code if applicable
  "peerDependencies": { "svelte": "^5" } // teach the user to install svelte
}

If your svelte component needs special preprocesors, you can also publish the compiled module:

// package.json
{
  "svelte": "./dist/Button.js", // no svelte bundled in
  "peerDependencies": { "svelte": "^5" }
}

If you only want to do some code splitting works, that's not fully supported. You can search for manual chunks in the issues.

dennisfrijlink commented 1 week ago

That means it's not possible to define multiple svelte components in one project and compile them each to a separate js file + a separate js file for the svelte runtime?

hyrious commented 1 week ago

It is possible.

BTW compiling svelte code has nothing to do with esbuild. The svelte compiler works separately on each svelte component file to produce the js code. (This is already your expected "separate js file".)

dennisfrijlink commented 4 days ago

BTW compiling svelte code has nothing to do with esbuild. The svelte compiler works separately on each svelte component file to produce the js code. (This is already your expected "separate js file".)

So that means after building I can easily use componentA on site 1 and componentB on site 2? (where componentA and componentB are from the same Svelte project).