I know you can't conditionally require
a module with browserify because they're bundled at compile time, not run time. How about conditionally stripping modules?
Let's say I have an app that allows you to create image galleries. The galleries can also be edited (reordering images etc.). But the rendering of the gallery and the editing are coupled and can't be fully separated. But for deploying the galleries I don't need the editing functionality and I know which modules are used. I want to create two different bundles, one with editing capabilities and one without by eliminating most of the editing code. What I did is use envify
and uglify's dead code elimination to exclude my own code from the smaller bundle.
Before (thing.js)
//...some code that only the editor needs...
module.exports = thing;
After (thing.js)
if(process.env.INCLUDE_EDITOR === 'yes') {
//...some code that only the editor needs...
module.exports = thing;
}
This works great and the editor bundle is already smaller. And since I know that the other bundle will never use the functionality of thing
it's OK to just export nothing and have an empty module.
Now here's the problem. If thing.js
requires a module, say pica
, it will still be bundled even though nobody uses it after dead code elimination.
Before (thing.js)
var pica = require('pica');
//...some code that uses pica...
module.exports = thing;
After (thing.js)
if(process.env.INCLUDE_EDITOR === 'yes') {
var pica = require('pica');
//...some code that uses pica...
module.exports = thing;
}
To sum it up: my bundle now contains the pica
library, but nobody requires it. The code that required it was dead code, but uglify can obviously not understand that it could remove pica
completely.
I think what you are after is a transform like
uglifyify
.Take note that you will still want to run
uglifyjs
on the resulting output.