React SSR环境下引入FullCalendar报错:$.extend is not a function
Hey there, let's work through this FullCalendar error you're hitting in your React SSR project. The issue boils down to how legacy FullCalendar versions (like v3 and earlier) rely on a globally available jQuery instance with all core methods intact—here's how to fix it:
Why This Happens
FullCalendar's older codebase depends on the global $/jQuery object to access utility methods like $.extend. Even if you've imported jQuery locally, if it's not exposed globally or you're using a stripped-down "slim" version of jQuery, FullCalendar can't find the method it needs. SSR adds another layer of complexity since the window object doesn't exist on the server, so we have to handle environment differences carefully.
Step-by-Step Solutions
1. Confirm You're Using the Full jQuery Build
First, make sure you're not using the jquery-slim package—it removes core utilities like $.extend to reduce file size. Swap to the full version if needed:
npm uninstall jquery-slim npm install jquery
2. Expose jQuery Globally (Client-Side Only)
Since SSR runs on the server where window isn't available, we need to conditionally attach jQuery to window only in the browser. Add this to your main entry file (e.g., src/index.js):
import $ from 'jquery'; // Only expose jQuery globally in the browser environment if (typeof window !== 'undefined') { window.$ = $; window.jQuery = $; } // Import FullCalendar AFTER ensuring jQuery is available import 'fullcalendar'; import 'fullcalendar-scheduler';
3. Use Webpack's ProvidePlugin for Auto-Injection
To avoid manually importing jQuery in every file, configure Webpack's ProvidePlugin to automatically inject jQuery into modules that expect it. Update your webpack.config.js:
const webpack = require('webpack'); module.exports = { // ... rest of your existing config plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' // Ensures FullCalendar detects the global instance }) ] };
4. Double-Check Import Order
Always import jQuery before FullCalendar and FullCalendar Scheduler. If FullCalendar loads first, it'll try to access $.extend before jQuery is initialized, triggering the error.
Bonus: Upgrade to FullCalendar v5+ (Long-Term Fix)
If you're open to refactoring, FullCalendar v5 and above are completely jQuery-free and built to integrate smoothly with modern frameworks like React. This eliminates jQuery dependency issues entirely, though it will require updating your FullCalendar implementation code.
内容的提问来源于stack exchange,提问作者Kailash Chandra

