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

如何在Laravel-Vite配置中定义jQuery并全局供外部库使用?

解决Vite开发模式下jQuery全局未定义的问题

问题原因

Vite默认将app.js作为ES模块加载,模块代码的执行是异步的;而你引入的x.jquery.min.js是普通同步脚本,会在app.js模块中的window.jQuery = jQuery执行前就运行,导致找不到jQuery变量。

解决方案

方案1:通过动态加载确保脚本执行顺序

修改index.blade.php中的脚本引入方式,等待app.js加载完成后再加载依赖jQuery的外部脚本:

<script type="module">
  // 先加载并执行app.js
  await import('./app.js');
  // 动态创建并加载外部脚本
  const externalScript = document.createElement('script');
  externalScript.src = 'x.jquery.min.js';
  document.body.appendChild(externalScript);
</script>

方案2:在全局注入jQuery(无需手动挂载window)

修改vite.config.js,配置Vite自动将jQuery注入到全局作用域,这样不需要在bootstrap.js中手动设置window.jQuery:

import { defineConfig } from 'vite';

export default defineConfig({
  resolve: {
    alias: {
      'jquery': 'jquery/dist/jquery.min.js' // 配置jQuery别名,可选
    }
  },
  build: {
    rollupOptions: {
      output: {
        globals: {
          jquery: 'jQuery' // 将jQuery暴露为全局变量jQuery
        }
      }
    }
  },
  // 开发模式下全局注入
  optimizeDeps: {
    include: ['jquery']
  }
});

然后在bootstrap.js中只需导入jQuery即可:

import jQuery from 'jquery';
// 无需手动挂载window,Vite已帮你全局注入

方案3:通过自定义事件同步加载时机

  1. 修改bootstrap.js,挂载jQuery后触发自定义事件:
import jQuery from 'jquery';
window.jQuery = jQuery;
window.$ = jQuery; // 可选,同时挂载$
// 触发自定义事件通知外部脚本jQuery已就绪
document.dispatchEvent(new Event('jQueryReady'));
  1. 修改index.blade.php,监听事件后加载外部脚本:
<script src="app.js"></script>
<script>
document.addEventListener('jQueryReady', function() {
  const script = document.createElement('script');
  script.src = 'x.jquery.min.js';
  document.body.appendChild(script);
});
</script>

注意事项

  • 确保已通过npm install jquery安装jQuery依赖
  • 若使用方案2,需保证Vite配置生效,开发服务器需重启

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:31:25