Webpack中通过import引入jQuery后报错:$ is not defined、jQuery is not defined
Hey, I've run into this exact issue before when migrating jQuery to Webpack—let me break down why it's happening and how to fix it!
Why This Happens
The core problem is Webpack's module scoping behavior. Unlike loading jQuery via a <script> tag (which dumps $ and jQuery directly onto the global window object), Webpack wraps imported modules in isolated function scopes by default. That means even though you've imported jQuery in your JS file, it's not accessible to the global browser environment (like inline scripts on your page) or to libraries like Bootstrap that expect jQuery to be globally available.
Fixes to Try
1. Use Webpack's ProvidePlugin (Best for Most Cases)
This plugin does two things: it automatically injects jQuery into every module that references $ or jQuery, and ensures the global window object has access to them (critical for Bootstrap and inline scripts).
First, update your webpack.config.js:
const webpack = require('webpack'); module.exports = { // ... your existing config plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }) ] };
Then, in your main entry JS file, explicitly mount jQuery to window (this ensures no edge cases where the plugin doesn't sync properly):
import $ from 'jquery'; window.$ = $; window.jQuery = $; // Now Bootstrap will find the global jQuery it needs import 'bootstrap';
2. Import jQuery Locally (For Fully Modular Projects)
If your project has no inline scripts relying on global $, you can skip global injection and just import jQuery directly in the modules that need it:
import $ from 'jquery'; import 'bootstrap'; // Use $ normally within this module $(document).ready(() => { console.log('jQuery works here!'); });
Note: This won't fix errors from inline scripts, since $ won't exist on the global window.
3. Use expose-loader (For Webpack 4 or Older)
If you're stuck on an older Webpack version, expose-loader can force jQuery to be exposed globally.
First install the loader:
# npm npm install expose-loader --save-dev # Yarn yarn add expose-loader --dev
Then update your entry file:
import 'expose-loader?$!jquery'; import 'expose-loader?jQuery!jquery'; import 'bootstrap';
Or configure it in webpack.config.js for cleaner imports:
module.exports = { module: { rules: [ { test: require.resolve('jquery'), use: [ { loader: 'expose-loader', options: '$' }, { loader: 'expose-loader', options: 'jQuery' } ] } ] } };
Quick Note for Bootstrap
Bootstrap requires jQuery to be available on the global window object to initialize properly. No matter which fix you choose, make sure window.jQuery is set before importing Bootstrap.
内容的提问来源于stack exchange,提问作者Mike Lammers

