Skip to content

Instantly share code, notes, and snippets.

@kottenator
Last active May 21, 2019 18:17
Show Gist options
  • Save kottenator/0623cf601ea167f31cfb3150d8b25b10 to your computer and use it in GitHub Desktop.
Save kottenator/0623cf601ea167f31cfb3150d8b25b10 to your computer and use it in GitHub Desktop.
jQuery plugin with browserify-shim

Goal

Demonstrate how to configure browserify with browserify-shim to exclude jQuery from the bundle and to make jQuery plugin (that supports CommonJS modules) work correctly, using global window.jQuery object.

Step 1: create files

index.html:

<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="index.bundle.js"></script>
<div id="circle"></div>

index.js:

import $ from 'jquery';
import 'jquery-circle-progress'; // this should work too: import $ from 'jquery-circle-progress';
$(() => $('#circle').circleProgress({value: 0.7}));

package.json

{
  "private": true,
  "dependencies": {
    "jquery": "*",
    "jquery-circle-progress": "*"
  },
  "devDependencies": {
    "browserify": "~13.1",
    "browserify-shim": "~3.8",
    "babelify": "~7.3",
    "babel-preset-es2015": "~6.16"
  },
  "browserify-shim": {
    "jquery": "global:jQuery"
  },
  "scripts": {
    "bundle": "browserify -t [ babelify --presets=babel-preset-es2015 ] -t [ browserify-shim --global ] index.js > index.bundle.js"
  }
}

Step 2: install

npm install

Step 3: bundle

npm run bundle

Step 4: check if it works

Open index.html in browser - animated circle should appear, no JS errors should raise in the console.

Step 5: check the bundle

Check index.bundle.js - there should be no jQuery bundled.

@mikehaertl
Copy link

@kottenator Sorry if this is a little late, but did this ever work for you? For me only require('jquery') works, not import 'jquery';

I currently try to compile Bootstrap4 plugins with jQuery included from CDN. They use import $ from jquery; everywhere and all I get is:

Error: Cannot find module 'jquery'

But I don't want to touch the BS4 plugin files. Any ideas would be much appreciated.

@mikehaertl
Copy link

Answering myself. The solution is actually pretty obvious - once you know it. I had to change the order of browserify transforms from

  "browserify": {
    "transform": [
      "browserify-shim",
      [
        "babelify",
        {
          "presets": [
            "@babel/preset-env"
          ]
        }
      ]
    ]
  },

to

  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "@babel/preset-env"
          ]
        }
      ],
      "browserify-shim"
    ]
  },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment