From 714bf38b51e6a0094392f8628d3f959b48776957 Mon Sep 17 00:00:00 2001 From: Giacomo Balli Date: Mon, 6 Apr 2026 13:41:12 -0700 Subject: [PATCH] Make optional jQuery require bundler-friendly (#4184) The literal `require('jquery')` form (even inside try/catch) is statically analyzed by Webpack, Rollup, esbuild and packd, so users who do not actually want jQuery still see their bundles fail with "Cannot find module 'jquery'". Indirect the optional require through a variable that bundlers do not follow: var nodeRequire = typeof require === 'function' && require; try { if (nodeRequire) $ = nodeRequire('jquery'); } catch (e) {} Behavior is unchanged: jQuery remains optional, the try/catch still swallows the runtime ENOENT in Node, and `Backbone.$` is still set when jQuery is installed. Also declare `jquery` as an optional peerDependency in package.json so npm/yarn/pnpm document the relationship cleanly without forcing the install. --- backbone.js | 8 +++++++- package.json | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/backbone.js b/backbone.js index 5bfd974cd..34735edde 100644 --- a/backbone.js +++ b/backbone.js @@ -23,7 +23,13 @@ // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $; - try { $ = require('jquery'); } catch (e) {} + // Indirect the optional jQuery require through a variable so that + // Webpack, Rollup, esbuild, packd and friends do not try to resolve + // it at bundle time. The literal `require('jquery')` form was being + // statically analyzed by bundlers and failing the build for users + // who don't actually want jQuery (#4184). + var nodeRequire = typeof require === 'function' && require; + try { if (nodeRequire) $ = nodeRequire('jquery'); } catch (e) {} factory(root, exports, _, $); // Finally, as a browser global. diff --git a/package.json b/package.json index bcb6349ff..6e66a43c4 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,14 @@ "dependencies": { "underscore": ">=1.8.3" }, + "peerDependencies": { + "jquery": ">=1.11.0" + }, + "peerDependenciesMeta": { + "jquery": { + "optional": true + } + }, "devDependencies": { "coffeescript": "^2.7.0", "cpy-cli": "^5.0.0",