Laravel 10集成Bootstrap 5时出现bootstrap is not defined错误
Laravel 10 + Vite 下 Bootstrap JS 未定义问题解决
问题现象
使用 Laravel 10 搭配 Vite,通过 NPM 安装 Bootstrap 后,CSS 和 Bootstrap Icons 可正常加载,但 Bootstrap JS 功能(如模态框、提示框、弹出框)无法使用,控制台报错 bootstrap is not defined,例如在页面中调用 bootstrap.Toast 时触发错误。
当前配置代码
vite.config.js
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import path from 'path'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.js'], refresh: true, }), ], resolve: { alias: { '~bootstrap': path.resolve(__dirname, "node_modules/bootstrap"), '~bootstrap-icons': path.resolve(__dirname, "node_modules/bootstrap-icons/font") } } });
resources/js/app.js
import * as bootstrap from 'bootstrap';
主布局 blade.php
... @vite(['resources/css/app.css', 'resources/js/app.js']) ...
报错页面代码片段
... <script> window.onload = () => { const toastLiveExample = document.querySelector("#liveToast") const toast = new bootstrap.Toast(toastLiveExample) toast.show() } </script> ...
问题原因
ES 模块的 import 具有模块作用域,你在 app.js 中导入的 bootstrap 对象仅存在于模块内部,并未挂载到全局 window 对象上,因此页面中的普通 <script> 无法直接访问到该对象。
解决方案
方案一:将 Bootstrap 挂载到全局 window 对象
修改 resources/js/app.js,把导入的 bootstrap 赋值给 window.bootstrap,使其成为全局变量:
import * as bootstrap from 'bootstrap'; window.bootstrap = bootstrap;
修改后重新运行 npm run dev 或 npm run build,页面中的 bootstrap 对象即可正常访问。
方案二:将页面脚本改为 ES 模块
把页面中的普通 <script> 改为 type="module",并在脚本内部导入 Bootstrap:
... <script type="module"> import * as bootstrap from 'bootstrap'; window.onload = () => { const toastLiveExample = document.querySelector("#liveToast") const toast = new bootstrap.Toast(toastLiveExample) toast.show() } </script> ...
这种方式无需修改 app.js,但每个需要使用 Bootstrap JS 的页面都要这样处理,适合仅个别页面使用的场景。
内容的提问来源于stack exchange,提问作者user22453190
相关产品推荐
相关产品推荐

