Having trouble creating a static site using @sveltejs/adapter-static when Bootstrape is installed

I started my project with SvelteKit by running npm create svelte@latest my-app

Afterwards, I included Bootstrap in the project using npm install bootstrap. Then I imported Bootstrap's css and js files into the root layout as shown below:

The content of src/routes/+layout.svelte

<script>
    import 'bootstrap/dist/css/bootstrap.min.css';
    import 'bootstrap/dist/js/bootstrap.min.js';
    import Header from './Header.svelte';
    import './styles.css';
</script>

<div class="app">
    <Header />

    <main>
        <slot />
    </main>

    <footer>
        <p>visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to learn SvelteKit</p>
    </footer>
</div>

<style>
</style>

The configuration in svelte.config.js

import adapter from '@sveltejs/adapter-static';

export default {
    kit: {
        adapter: adapter({
            pages: 'build',
            assets: 'build',
            fallback: null,
            precompress: false,
            strict: true
        })
    }
};

npm run dev is working fine, but when I try to run npm run build, I encounter an error:

ReferenceError: document is not defined
    at K (/home/alok/Alok/myapp/node_modules/bootstrap/dist/js/bootstrap.min.js:6:8846)
    (...)
[vite-plugin-sveltekit-compile] Failed with code 1
error during build:
Error: Failed with code 1
(...)

Am I adding Bootstrap incorrectly? How can I successfully build this project to generate a static site?

Answer №1

Server-side rendering does not allow the use of the document object, as it is not defined at that level. To work around this limitation, you can import all document-related methods in one component and then import that component into your layer like so:

<script>
...
let Slider;
onMount(async () => {
    const module = await import('./components/Slider.svelte');
    Slider = module.default;
});
...
<svelte:component this={Slider}/>

If your Slider.svelte component includes Bootstrap imports, by importing it inside onMount, you are bypassing server-side rendering entirely and avoiding any errors related to the document object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js Express application does not recognize the custom module being used

We've encountered an error with a custom module for our express app. The error message says somename is not defined Below is the code snippet causing the issue: app.js var express = require('express'); var path = require('path') ...

Exploring Web Application Testing using Vows and Tobi

Just diving into the world of node.js testing and could use some guidance. I'm looking to run some basic tests on my express webapp using vows and tobi, such as checking if the login route functions properly. var vows = require('vows'); v ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Utilize React JS to incorporate multiple instances of the Bootstrap carousel within a webpage using Reactstrap

I am having difficulty using the bootstrap carousel multiple times on a single page. I have attempted to copy it as a new item numerous times, but I keep encountering errors. <CarouselItem onExiting={() => setAnimating(true)} onExited={() => ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

Dealing with the "undefined callback" error in Node.js while attempting an HTTP request

I'm brand new to Node.js and I'm struggling with this callback concept. Currently, I'm developing a Skill for an Amazon Echo that involves sending an SMS via a HTTP Request using BulkSMS.com. The http.request function includes a callback to ...

Authentic edition of link with node v0.8.1

Seeking advice on compatibility between connect v2.3.5 and Node 0.8.1, has anyone tested this combination for stability? I am currently working with express v2.5.11 on Ubuntu 11 and open to using an older version of connect that is compatible with node 0 ...

Encountering an error when attempting to connect a nodejs REST API to an HTTPS URL using port 844

Attempting to initiate an API call from Node.js to a Tomcat server using the http/https module. There are two options for the API URL: - Functioning correctly and receiving a response var options = { host: 'samleapiurl.com', port: ...

"Efficient Email Processing: Streamlining Transactions and Bulk Communications

What are the most effective strategies for utilizing both transactional and marketing email? Currently, I am exploring Mailgun for transactional emails because of their free API that aligns with my needs. As my usage grows, they offer affordable pricing p ...

Using additional arguments for callback functions in MySQL queries within a Node.js environment

I am attempting to execute a MySQL query using Node.js and I need to pass additional parameters in the callback function. for (let i = 0; i < categories.length; i++) { connection.query ('select * from products where category=' + categorie ...

What are the steps for transitioning a HTTP stream to HTTPS?

Currently, my website operates on HTTPS through a public hoster and is connected to a Raspberry PI running a node server. In the same network as the PI, there is a hardware component (referred to as decoder) that transmits a data stream via TCP. The purpo ...

What is the proper way to reference an EJS function that is declared in a different EJS file?

document 1: jsfunction.ejs <% function testFunction() {return 42;} %> file 2: data.ejs <% include jsfunction.ejs %> <% testFunction(); %> result: ReferenceError: 1| <% include jsfunction.ejs %> >> 2| <% testFuncti ...

Guide to converting audio files to HLS format using fluent-ffmpeg in Node.js

For my project, I utilized the following code snippet: ffmpeg.setFfprobePath(ffprobeBin.path); ffmpeg.setFfmpegPath(ffmpegPath); ffmpeg(audioPath, {timeout: 432000}) .audioCodec('aac') .audioBitrate('128k') .outputOptions([& ...

Implement a basic JavaScript prompt feature within a Node.js application that can be integrated into

My Angular App is wrapped by electron and utilizes node.js to fetch MySQL data for AngularJs via electron. However, since there is no fixed database in my project, I have to dynamically change the database credentials from the client side, making sure it p ...

Transferring Session ID between Express.js and Socket.io while dealing with iframes from distinct origins

My Node application built with Express.js and Socket.io is facing an issue where they are not sharing the same session ID when running under iframe with different origins. When accessed directly or through iframes with the same origin, everything works fin ...

Fetching items from a MongoDB collection using an array of unique identifiers

Creating an API using node.js/express and MongoDB. I have two collections that are related in a many-to-many way, Users and Items. My goal is to retrieve all the items that a user is following. Each user has an array of item IDs. How can I query to fetch ...

Jade includes an apostrophe when generating the output

Does anyone know why this Jade template keeps adding apostrophes around variable outputs no matter what I do? The code snippet below shows how it's displaying in the document at the end. Any suggestions? div.col-md-4.col-xs-12 div#currentImg ...

What is the recommended way to integrate Auth0 with a RESTful API?

Recently, I've been considering incorporating Auth0 for user authentication in my nodejs API. To add to the mix, I'm utilizing a MySQL database for user sign-ins and also want to implement Facebook login functionality. However, I've hit a r ...

The best practices for handling assets (css) in MEAN.js and Node.js

MEAN.js utilizes configuration files for managing CSS files, as well as automatically loading all CSS files for each module. Query #1: What is the method to exclude specific files from the list? Query #2: How can a particular CSS file be included only on ...

Utilizing the express framework to dynamically render route requests

I'm interested in trying dynamic routing with the express framework for my Node.js server. Here is an example of how I am attempting to achieve this: <a href="/views/adminpanel?url={{mMenu.WebAddress}}" ng-click="Description(mMenu.WebAddress)"> ...