How do I manage relative path aliasing in multiple grunt-browserify bundles?

Simple answer:

The simplest is to use the paths option of browserify. I use it for some months with great success. I have even made a starter kit that uses this feature: https://github.com/stample/gulp-browserify-react-phonegap-starter

var b = browserify('./app', {paths: ['./node_modules','./src/js']});

paths – require.paths array to use if nothing is found on the normal
node_modules recursive walk

If you have a file in src/js/modulePath/myModule.js this won’t let you write require("myModule") everywhere, but rather require("modulePath/myModule"), from any of your other source files.

Deprecated option?

It does not seem so!

The Browserify module resolution algorithm mirrors the resolution algorithm in NodeJS.
The paths option of Browserify is thus the mirror of NODE_PATH env variable behavior for NodeJS.
The Browserify author (substack) claims in this SO topic that the NODE_PATH option is deprecated in NodeJS and thus it is also deprecated in Browserify and could be removed in next versions.

I do not agree with this claim.

See the NODE_PATH documentation. It is not mentionned that the option is deprecated. However there is still an interesting mention that does in the direction of substack’s claim:

You are highly encouraged to place your dependencies locally in
node_modules folders. They will be loaded faster, and more reliably.

And this question has been posted in 2012 on the mailing list.

Oliver Leics: is NODE_PATH deprecated? 
Ben Noordhuis (ex core NodeJS contributor): No. Why do you ask? 

And if something is not removed in NodeJS resolution algorithm, I don’t think it will be removed anytime soon from Browserify 🙂

Conclusion

You can either use paths option or put your code in node_modules like the official documentation and Browserify author recommends.

Personally, I don’t like the idea to put my own code in node_modules as I simply keep this whole folder out of my source control. I use the paths option for some months now and did not have any problem at all, and my build speed is pretty good.

The substack’s solution of putting a symlink inside node_modules could be convenient but unfortunately we have developers working with Windows here…

I think there’s however a case where you don’t want to use the paths option: when you are developping a library published on an NPM repository that will be required by other apps. You really don’t want these library clients to have to setup special build config just because you wanted to avoid relative path hell in your lib.

Another possible option is to use remapify

Leave a Comment