You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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',
        },
    },
});

验证步骤

  1. 执行npm run dev重新编译资源
  2. 刷新页面,检查控制台是否还存在Bootstrap依赖jQuery的报错

内容的提问来源于stack exchange,提问作者vimuth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:27:09