I ve been looking for a proper way to import Bootstrap into a SvelteKit project, where Bootstrap is installed using npm. Importing the CSS is quite straightforward since I prefer compiling the CSS file using SASS. I create a file in src/assets/scss
named main.scss
(here s an example based on Bootstrap s "Option A" - note the extra ../../
):
@import "../../../node_modules/bootstrap/scss/bootstrap";
This is compiled to src/static/css/main.css
and then imported in the app.html
file.
app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="/css/main.css" /> <!-- HERE -->
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
So far so good. Things get trickier when trying to import Bootstrap from node_modules
. There are different Stackoverflow answers (such as this one) that claim you can simply import bootstrap.min.js
in the script
tag. However, this gives me a "document is not defined" error. I understand this is because the document has not yet loaded - SvelteKit provides the browser
module to get around this. I can import Bootstrap properly with the following code:
<script>
import { browser } from $app/environment ;
let bootstrap;
async function loadBootstrap() {
bootstrap = await import( bootstrap );
// do stuff with bootstrap here
}
if (browser) loadBootstrap();
</script>
While this works, I have to repeat the same lines of code every time I want to instantiate Bootstrap, for example when I want to manually show a modal. I m wondering if there s a reason why the solution provided in the above Stackoverflow answer doesn t work, and if it s wrong, whether I could be loading Bootstrap in a cleaner way.