Webpack 4升级后jQuery注入异常 第三方插件无法调用求助
This is a super common pain point when moving to Webpack—let’s break down why it’s happening and how to fix it quickly:
Why this occurs
You’re loading jQuery via a <script> tag globally, but Webpack’s module system might be pulling in a second, separate jQuery instance for your bundled code or third-party plugins. Even though $ works in your own code, those plugins are grabbing the wrong instance (or looking for it in the wrong scope).
Step-by-step fixes
Tell Webpack to use the global jQuery (don’t bundle it)
Add these configurations to yourwebpack.config.jsto ensure Webpack doesn’t package its own jQuery, and maps all module references to the global instance:const webpack = require('webpack'); module.exports = { // ... rest of your existing config externals: { // Declare jQuery as an external global variable Webpack should use jquery: 'jQuery' }, plugins: [ // Make $, jQuery, and window.jQuery available to all modules automatically new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }) ] };The
externalskey tells Webpack: "Don’t bundle jQuery into the bundle—use the one already available globally". TheProvidePlugininjects the global jQuery into any module that references$orjQuery, so your bundled code uses the exact same instance as the<script>tag you added.Confirm load order
Since you’re loading jQuery via a<script>tag in the head, make sure it loads before your Webpack bundle. If Yii2 manages your assets, update yourAssetBundleto depend on your jQuery asset (even if you’re loading it manually, just ensure the jQuery script tag comes first in the DOM).Remove duplicate jQuery imports
Scan your codebase for anyimport 'jquery'orrequire('jquery')statements. If you find them, delete them—Webpack will now use the global instance instead of pulling in a fresh copy.Verify the instance match
Add a quick test in your bundled code to confirm everything’s using the same jQuery:console.log($ === window.jQuery); // Should log trueIf this returns
true, your bundled code is aligned with the global instance. If plugins still fail, check if they have hardcoded jQuery detection (some older plugins look specifically forwindow.jQuery—ourProvidePluginalready maps that, but it’s worth double-checking).
Bonus: Yii2 AssetBundle tip
If you’re using Yii2’s asset system to load your Webpack bundle, define a dependency on your jQuery asset to enforce correct load order automatically:
class AppBundle extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $js = [ 'dist/app.bundle.js', // Your Webpack-built bundle ]; public $depends = [ // Replace with your custom jQuery asset bundle 'app\assets\JqueryAsset', ]; }
That should align all your code and third-party plugins to use the same global jQuery instance. Let me know if you hit any odd edge cases!
内容的提问来源于stack exchange,提问作者Miro Hudak

