Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jdeagle/f0b5a5e026318aff2fc6 to your computer and use it in GitHub Desktop.
Save jdeagle/f0b5a5e026318aff2fc6 to your computer and use it in GitHub Desktop.

If you are using backbone (and backbone.marionette) in a browserify managed project, you will likely run into issues with underscore (at least if you manage your dependencies with npm). Each package, that has underscore as a dependency, will require its own version of underscore (making your bundle file contain multiple versions of underscore). Back in the days, you could shim backbone and underscore like:

browserify({
	shim: {
		'underscore': {
			path: './node_modules/underscore/underscore.js',
			exports: '_'
		},
		'backbone': {
			path: './node_modules/backbone/backbone.js',
			exports: 'Backbone',
			depends: {
				'jquery': '$',
				'underscore': '_'
		    	}
	    	}
	    }
	}
});

These days, underscore, backbone and backbone.marionette support CommonJS. Shimming these packages is not necessary anymore. But that also means, that you have no control over the package's dependencies. Luckily, there exists a browserify transform called aliasify. This package will transform the require paths of your local modules. If you want the transform to operate on your whole bundle, you need to use it directly within your browserify task, since you can not configure global transforms in a package.json like you can with ordinary transforms.

Have a look at browserify-task.js. The aliasify transform is applied globally. The aliasify transform can still be configurated within your package.json. Note: the browserify transform field should not contain aliasify, since it will only operate on your local modules.

If you want to replace all of the underscore requires with lodash, you can configure aliasify like:

{
	"aliasify": {
		"aliases": {
			"underscore": "./node_modules/lodash/dist/lodash.underscore.js"
		}
	}
}
var browserify = require('gulp-browserify'),
aliasify = require('aliasify');
var bundler = browserify({
// Configure browserify
});
bundler
// Global aliases (e.g. replaces underscore with lodash)
.transform({global: true}, aliasify)
.bundle();
{
"browserify": {
"transform": []
},
"aliasify": {
"aliases": {
"underscore": "./node_modules/lodash/dist/lodash.underscore.js"
}
},
"dependencies": {
"backbone": "^1.1.2",
"backbone.marionette": "^2.2.0",
"backbone.wreqr": "^1.3.1",
"jquery": "^2.1.1",
"lodash": "^2.4.1",
},
"devDependencies": {
"aliasify": "^1.4.0",
"browserify": "^5.11.1",
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment