Saturday 13 May 2017

Prevent bundling jQuery as a dependency with Browserify

So I have been searching all over the internet to try to find a solution to this problem but I cannot find a solution that works. I'm currently using the latest version of Gulp and Browserify to bundle up JS for the website I'm working on. We previously would concatenate all the JS files together, but I'm moving to a module setup now.

The problem I am running into is duplicating certain dependencies, in this example, I'll focus on jQuery (v2.1.4). Here is my setup:

main.js (Loaded on every page)

window.jQuery = window.$ = require('jquery');
window.Vue = require('vue');    
require('jquery-validation');

// More JS that loads on all pages

page.js (Each page has it's own js file for scripts relating to that page)

require('remodal'); // This requires jQuery

// Rest of the JS for this page...

The problem I am running into is that now jQuery is in both javascript bundles. With Browserify, I marked jQuery as "external" for page-speicific.js which removed jQuery from the script, but I get an error Uncaught Error: Cannot find module 'jquery' and I cannot seem to find a solution to this.

If I "exclude" jQuery with Browserify, or if I put a try block around the require('remodal'), I end up with Uncaught TypeError: $(...).remodal is not a function instead. I'm guessing since the module remodal requires jQuery and it's not loaded there, it's not seeing it's set to the window and that's why execution fails?



via Devin

No comments:

Post a Comment