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

Webpack打包jQuery插件后出现jQuery未定义错误,新手求助

解决Webpack打包jQuery插件后全局未定义的问题

Hey there! Let's break down why you're seeing that Uncaught ReferenceError: jQuery is not defined error, even though you're loading plugins-bundled.js first.

The core issue here is that Webpack wraps all modules in its own isolated scope by default. That means even if you bundle jQuery into plugins-bundled.js, it won't automatically be exposed to the global window object. Since your scripts.js is running in the global environment, it can't access the jQuery instance that's trapped inside Webpack's module scope.

Here are two reliable fixes to get this working:

方法1:手动将jQuery挂载到全局(简单直接)

Create a dedicated entry file for your plugins (let's call it plugins-entry.js) instead of bundling directly from a random path. In this file, explicitly attach jQuery to the window object after importing it:

// plugins-entry.js
// Import jQuery
import $ from 'jquery';
// Expose it globally so scripts.js can access it
window.jQuery = window.$ = $;

// Now import your jQuery plugins (they'll use the global jQuery instance)
import 'your-first-jquery-plugin';
import 'another-jquery-plugin';

Then update your Webpack config's entry to target this file for plugins-bundled.js:

module.exports = {
  entry: {
    'plugins-bundled': './path/to/plugins-entry.js',
    // ... your other entries like App
  },
  // ... rest of your config
};

方法2:使用Webpack的expose-loader(更符合Webpack最佳实践)

If you prefer a config-based approach, use expose-loader to automatically expose jQuery to the global scope during bundling.

First, install the loader:

npm install expose-loader --save-dev

Then add this rule to your Webpack config's module.rules:

module.exports = {
  // ... other config
  module: {
    rules: [
      {
        test: require.resolve('jquery'),
        loader: 'expose-loader',
        options: {
          exposes: ['$', 'jQuery'], // Expose both $ and jQuery globally
        },
      },
      // ... your other loaders (like babel, css, etc.)
    ]
  }
};

This will ensure that whenever jQuery is imported in your plugins bundle, it's automatically attached to window.$ and window.jQuery.

关键检查点

  • Double-check that your plugins-bundled.js entry actually includes jQuery and all your plugins—Webpack won't bundle modules you don't explicitly import.
  • Make sure you're loading plugins-bundled.js before scripts.js in your HTML (you mentioned you're doing this, but it's worth verifying the script tags aren't misordered).

Once you implement either fix, your scripts.js should be able to access jQuery without any errors!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:35:25