英文:
How to import Bootstrap in SvelteKit, Recommended Way
问题
我正在使用SvelteKit构建网站。目前,我通过将Bootstrap 5添加到SvelteKit Skeleton项目提供的app.html文件中来包含它:
<!-- Bootstrap样式和JavaScript -->
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
现在,当我运行npm run build
来构建网站时,Bootstrap模块不再加载。
如果您需要更多信息,请告诉我。我对这方面还是新手。
感谢任何建议。
英文:
I am building a site with SvelteKit. As of now I included Bootstrap 5 in my project by adding it to the app.html file provided by the SvelteKit Skeleton project:
<!-- Bootstrap styles and javascript -->
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
Now when building the site with npm run build
the bootstrap modules are not loaded anymore.
If you need any more information please let me know. I am a beginner with this stuff.
Thanks for any advice
答案1
得分: 1
我可能会在顶级+layout.svelte
中导入这些文件。
大致如下:
<script>
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
</script>
<slot />
Vite会处理其余部分。(你也可以导入非压缩版本以获得更好的开发体验,因为构建应该会进行压缩。)
请注意,这会导致服务器端渲染问题,通常建议根据需要导入组件,如下所示:
import Alert from 'bootstrap/js/dist/alert';
// 或者,指定所需的插件:
import { Tooltip, Toast, Popover } from 'bootstrap';
您还可以导入样式源而不是已编译的样式。SvelteKit使用Vite,因此相应的Vite指南应适用。
如果您只想以与SSR兼容的方式导入所有内容,可以使用URL导入并将脚本标签添加到head
中,例如:
<script>
import 'bootstrap/dist/css/bootstrap.css';
import scriptSrc from 'bootstrap/dist/js/bootstrap.bundle.js?url';
</script>
<svelte:head>
<script src={scriptSrc}></script>
</svelte:head>
<slot />
英文:
I would probably just import the files in the top level +layout.svelte
.
Something along the lines of:
<script>
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
</script>
<slot />
Vite should take care of the rest. (You can also import the non-minified versions for a better dev experience, as the build should minify anyway.)
Note that this will cause issues with server-side rendering, and generally it is recommended to import components like this as necessary:
import Alert from 'bootstrap/js/dist/alert';
// or, specify which plugins you need:
import { Tooltip, Toast, Popover } from 'bootstrap';
You can also import style sources rather than the compiled styles.
SvelteKit uses Vite, so the respective Vite guidelines should be applicable.
If you just want to import everything in an SSR compatible way, you can use a URL-import and add a script tag to the head
, e.g.:
<script>
import 'bootstrap/dist/css/bootstrap.css';
import scriptSrc from 'bootstrap/dist/js/bootstrap.bundle.js?url';
</script>
<svelte:head>
<script src={scriptSrc}></script>
</svelte:head>
<slot />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论