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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With