如何仅在生产模式通过Webpack集成Bootstrap CDN及插件报错排查
Got it, let's break down why you're hitting this error and how to fix it:
Why the Error Happens
That "cannot read property 'var' of null" message almost always stems from Bootstrap's JavaScript trying to access jQuery's global variables, but something's off with your external dependencies setup:
- Your current config only includes Bootstrap's CSS via CDN, but Bootstrap 4's JS depends entirely on jQuery to run.
- You're still calling
require('bootstrap')inindex.js, but Webpack can't resolve that to a valid global variable because you haven't mapped Bootstrap's JS to a global in your externals config.
Step-by-Step Fix
Update the HtmlWebpackExternalsPlugin Config
You need to add Bootstrap's JS CDN entry to your externals, and ensure it loads after jQuery. Here's the revised working config:new HtmlWebpackExternalsPlugin({ externals: [ { module: 'jquery', entry: 'https://unpkg.com/jquery@3.2.1/dist/jquery.min.js', global: 'jQuery' }, { module: 'bootstrap', entry: [ // Load Bootstrap JS first (depends on jQuery being available) 'https://unpkg.com/bootstrap@4.0.0/dist/js/bootstrap.min.js', // Keep your existing CSS entry { path: 'https://unpkg.com/bootstrap@4.0.0/dist/css/bootstrap.min.css', type: 'css' } ], append: true, global: 'bootstrap' // Map require('bootstrap') to the global Bootstrap variable } ], enabled: isProd, })- Adding the Bootstrap JS entry tells Webpack to map
require('bootstrap')to the globalbootstrapvariable from the CDN, instead of trying to bundle it locally. - The order in the
entryarray ensures jQuery loads first, then Bootstrap JS, then Bootstrap CSS—this matches Bootstrap's dependency requirements.
- Adding the Bootstrap JS entry tells Webpack to map
Verify Global Variable Mapping
Double-check these details:- jQuery's
globalis set tojQuery(exactly what Bootstrap's JS expects to reference) - Bootstrap's
globalis set tobootstrap(the correct global variable exposed by Bootstrap 4's CDN JS)
- jQuery's
Confirm Production Mode Flag
Make sure yourisProdvariable is correctly evaluating totrueonly in production mode. If it's accidentallyfalse, the plugin won't inject the CDNs, and Webpack will try to bundle Bootstrap locally—leading to conflicts and errors.Clear Webpack Cache
Sometimes old cached bundles can cause unexpected issues. Delete your project's output folder (usuallydist/) or runrm -rf node_modules/.cacheto start fresh.
Final Check
After updating the config, build your production bundle and inspect the generated index.html—you should see the jQuery CDN link first, followed by Bootstrap JS, then Bootstrap CSS. This ensures all dependencies are loaded in the correct order, and require('bootstrap') will resolve to the properly initialized global variable.
内容的提问来源于stack exchange,提问作者Pushparaj

