1

I'd like to use Browserify but continue loading jQuery and jQuery UI from Google's CDN instead of concatenating the code into my files or my vendor bundle. I can't seem to figure out how to get it to work.

I am getting this error when loading foo.js:

Cannot find module 'jquery-ui'

These are the relevant files:

package.json

{
  // ...
  "devDependencies": {
    "browserify-shim": "^3.8.11",
    "deamdify": "^0.1.1",
    "grunt": "^0.4.5",
    "grunt-browserify": "^4.0.1"
  },
  "dependencies": {
    "jquery": "^2.1.4",
    "jquery-ui": "^1.10.5"
  },
  "browserify-shim": {
    "jquery": "global:$",
    "jquery-ui": {
      "depends": "jquery",
      "exports": null
    }
  }
}

Gruntfile.js

'use strict';

module.exports = function (grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        browserify: {
            options: {
                external: [
                    'jquery',
                    'jquery-ui'
                ],
                transform: [
                    'browserify-shim',
                    'deamdify'
                ]
            },
            app: {
                files: [{
                    expand: true,
                    cwd: 'public/js',
                    src: '*.js',
                    dest: 'assets/js'
                }]
            }
        }
    });

    grunt.loadNpmTasks('grunt-browserify');
};

foo.js

'use strict';

var $ = require('jquery');
require('jquery-ui');

$(document).ready(function () {
    console.log('Hello world');

    $('button').button();
});

I have also tried exclude instead of external and it produces the same results. Any way to achieve this?

I realize there's also the debowerify transform but I'd like to avoid Bower if possible.

Update: I've noticed that commenting out the require call to 'jquery-ui' will work because jQuery exposes the global $ and jQuery by default but I thought the whole point of writing code in CommonJS or even AMD format is to avoid depending on globals?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156

1 Answers1

1

You do not need the external block here. That's for excluding various libraries for your bundle...which is why when using the require('jquery-ui') with the external block you're getting that error.

What you want is to expose the global jquery-ui to your browserify builds, as here in the docs.

The browserify-shim config would be:

"browserify-shim": {
    "jquery": "global:$", // this is only if you're also loading jQuery via CDN/<script> tag
    "jquery-ui": {
      "depends": "jquery" 
    }
  }
YPCrumble
  • 26,610
  • 23
  • 107
  • 172