在SvelteKit中导入Bootstrap,避免“document is not defined”错误
在SvelteKit中正确导入Bootstrap的完整方案
一、为什么直接导入bootstrap.min.js会报错?
SvelteKit默认采用**服务端渲染(SSR)**模式,服务端执行代码时不存在浏览器环境的document对象。直接在组件<script>中同步导入Bootstrap JS,代码会先在服务端运行,自然抛出document is not defined错误。这类方案只适用于纯前端项目(如原生JS、非SSR的Svelte项目),没考虑SvelteKit的SSR特性。
二、更简洁的Bootstrap JS加载方式
你用browser判断的方案可行,但重复写代码效率低,可通过以下两种方式优化:
方式1:封装全局工具函数
在src/lib/utils/bootstrap.js中统一封装加载逻辑:
import { browser } from '$app/environment'; let bootstrapInstance = null; export async function getBootstrap() { if (browser && !bootstrapInstance) { bootstrapInstance = await import('bootstrap'); } return bootstrapInstance; }
后续在任意组件中直接调用:
<script> import { getBootstrap } from '$lib/utils/bootstrap'; async function openModal() { const bootstrap = await getBootstrap(); const modalElement = document.getElementById('exampleModal'); const modal = new bootstrap.Modal(modalElement); modal.show(); } </script> <button on:click={openModal}>打开模态框</button> <div class="modal fade" id="exampleModal">...</div>
方式2:利用SvelteKit的onMount钩子
onMount仅在浏览器端执行,无需额外判断browser:
<script> import { onMount } from 'svelte'; let bootstrap; onMount(async () => { bootstrap = await import('bootstrap'); // 初始化全局Bootstrap组件,比如工具提示 bootstrap.Tooltip.init(document.querySelectorAll('[data-bs-toggle="tooltip"]')); }); async function openModal() { const modal = new bootstrap.Modal(document.getElementById('exampleModal')); modal.show(); } </script>
若多个组件需要使用,可把onMount内的逻辑封装成复用函数。
三、CSS导入方案补充
你的SASS编译方案没问题,也可通过SvelteKit的vite.config.js配置自动引入,免去手动编译步骤:
// vite.config.js import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [sveltekit()], css: { preprocessorOptions: { scss: { additionalData: '@import "bootstrap/scss/bootstrap";' } } } });
之后在src/routes/+layout.svelte中引入全局样式(只需创建空的app.scss文件即可):
<script> import '../app.scss'; </script>
内容的提问来源于stack exchange,提问作者paulchoix
相关产品推荐
相关产品推荐

