Search code examples
javascripthtmlsveltesvelte-3svelte-component

can SVELTE.js function code become a package or library?


so I create the component in svelte, and add to it custom logic,
but compile it.

and then use native javascript to use the compiled version without doing the npm install of svelte.


basically, I want that the I can do something like this:

function test(text) {
 // for example let's add with native JS this component
 document.body.innerHTML += `<MyCard myParameter="${text}">` // when calling myCard it will create also some other child components and so on...
 
 // or 
 myCardSvelteFunction(10, 12); // take some parameters, but this function came from svelte script compiled instead not javascript
}

test("foo bar");
<script src="./mySvelteCompiled.js"></script>

<MyCard myParameter="hello world">

and this needs to not import svelte when development because technically we import the compiled version native javascript.



basically I have used a lot of javascript, and I very much liked the reusable code functions that you can make

by using <script src="https://example.com/script.js>

or import/export with type="module" attribute


in javascript is easy to write a function, copy the link of the script, call the function, and pass the parameters.

but since svelte is a compiled language I am wondering how can I make a function that can be used like it is a library

class object-oriented code in particular

this is because I have a very long vanilla js only code,
I want to refactor and rewrite better.


so I create the component in svelte, and add to it custom logic,
but compile it.

and then use native javascript to use the compiled version without doing the npm install of svelte.

is it possible?


want to know how the compiled code look like :

and it should in real time compile


Solution

  • Although it's still experimental, you can use the official svelte-package command to create a component library.