Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to require extensions with browserify

What is the best way is to include an extension for a common library like jQuery or Knockout with Browserify?

For example, with a project like knockout-switch-case, the global ko (knockout) variables is not passed to the module-definition call.

The AMD code for knockout-switch-case is:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['knockout'], factory);
    } else {
        // Browser globals
        factory(root.ko);
    }
}(this, function(ko) {

where it expects ko (knockout) to be a global on root, which would ordinarily be window but when using Browserify it is Object {}.

I have tried with the example using browserify-shim with something like this, but it did not work as expected (though it did work for knockout-mapping, which has a better module-dance):

  knockout:
    path: VENDOR_PATH + '/knockout.js'
    exports: 'ko'
    depends:
      jquery: '$'

I feel as though I must be overlooking something that must be quite obvious, as I expect this would be a fairly common module definition pattern for including any jQuery, Knockout or any other extension for a library that relies on a global. Or perhaps this is an issue fairly specific to something knockout-switch-case is doing.

In any case, thoughts and comments sincerely appreciated.

like image 743
Brian M. Hunt Avatar asked Nov 05 '13 02:11

Brian M. Hunt


Video Answer


1 Answers

This browserify-shim config works for me:

shim(browserify(), {
    jquery: {
        path: './js/vendor/jquery.js',
        exports: '$'
    },
    'knockout': {
        path: './js/vendor/knockout.js',
        exports: 'ko',
        depends: {
            jquery: '$'
        }
    },
    'knockout-switch-case': {
        path: './js/vendor/knockout-switch-case.js',
        exports: null,
        depends: {
            knockout: 'ko'
        }
    }
})

With that, you can require as usual: var ko = require('knockout');

like image 137
Lars Höppner Avatar answered Sep 22 '22 08:09

Lars Höppner