javascripttwitter-bootstrapbootstrap-5sveltesveltekit

Svelte5 and Bootstrap5


I have recently been getting into Svelte and really like it. It's my first framework with the binding stuff, and I have been enjoying just working on some personal projects with it.

However, I am having a hell of a time getting bootstrap5 working. Now, I am able to import both the style sheets and the javascript from the CDN. I was also able to load the js locally as well within the app.html.

However, I now want to be able to open a modal without a button being pressed (I actually don't really want this for my project, but I suspect it will come up again eventually so I've been trying to get this to work. It DOES work with "data-target" tags and everything. I am trying to reference bootstrap.Modal from the page.svelte.

So I have the following issues when I try to do this:

  1. Trying to import the library within the +page.svelte at the top of the script with a 'import bootstrap from "$lib/bs5/bootstrap.bundle.min.js"' causes an error with the message "document is not defined". I am assuming this is because the js file is trying to reference document, and that would need to be done with the svelte onmount. But I dont seem to be able to find a way to import within an onmount.

  2. Removing the import statement and just loading the js locally does let me reference "bootstrap.Modal" which is what I need, but VS Code/typescript does not allow me to use intellisense, and constantly claims there is an error since it has no reference to bootstrap.Modal. Admittedly this works, but I was assuming/hoping there is something I am missing that would make this part work. To be clear - this does work functionally, but no intellisense and the file always reporting an error.

I saw "sveltestrap", but that seems a bit over the top to me... I just want to be able to use the same things I see in the official bootstrap documentation, and sveltestrap seems to have a lot of differences.

Has anyone had experience with this before? Would love to be able to get that error cleared up.


Solution

  • Importing the Bootstrap bundle with an import statement within a Svelte component doesn't work. What you need to do is import it using a <script> tag from within app.html, the root page. I would put it at the end of the <body> tag, but exact positioning is not critical.

    As for typing. If you visit the package page at npmjs.com, you'll see a "DT" icon on top (see screenshot). If you hover with your mouse, it tells you that the package has a sibling package called @types/bootstrap that provides typing. Install it and you'll have Intellisense.

    Bootstrap package page