Laravel Vite集成Bootstrap3时提示依赖jQuery的错误求助
解决Laravel Vite中Bootstrap 3依赖jQuery的报错问题
问题原因
Bootstrap 3的JavaScript依赖全局作用域中的jQuery或$对象,但Vite默认采用ES模块化导入,导入的jQuery仅存在于模块内部,不会自动挂载到window对象上,导致Bootstrap初始化时找不到jQuery。
解决方案(两种任选其一)
方案1:手动将jQuery挂载到全局window对象
修改resources/js/register.js的导入逻辑,先导入jQuery并挂载到全局,再导入依赖库:
// 先导入jQuery并挂载到全局 import $ from 'jquery'; window.jQuery = window.$ = $; // 再导入依赖jQuery的库 import 'bootstrap/dist/js/bootstrap.min.js'; import 'jquery-steps/build/jquery.steps.min.js'; import 'jquery-validation/dist/jquery.validate.js'; var form = $("#example-form"); form.steps({ headerTag: "h6", bodyTag: "section", transitionEffect: "fade", titleTemplate: '<span class="step">#index#</span> #title#' });
方案2:通过Vite配置全局变量
修改vite.config.js,添加全局变量定义和jQuery别名,让Bootstrap能直接找到全局的jQuery:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; export default defineConfig({ plugins: [ laravel({ input: [ 'resources/css/app.css', 'resources/css/register.css', 'resources/js/register.js', 'resources/js/app.js', ], refresh: true, }), ], // 定义全局变量,让Bootstrap能识别到jQuery define: { 'window.jQuery': 'jQuery', 'window.$': 'jQuery', }, // 设置jQuery的别名,确保导入路径正确 resolve: { alias: { 'jquery': 'jquery/dist/jquery.min.js', }, }, });
验证步骤
- 执行
npm run dev重新编译资源 - 刷新页面,检查控制台是否还存在Bootstrap依赖jQuery的报错
内容的提问来源于stack exchange,提问作者vimuth
相关产品推荐
相关产品推荐

