Javascript conditional inclusion pre-minification: does such a tool exist?
All JS minifiers that I can find work by a combination of whitespace elimination, variable renaming, and regular compression. However, much more could be cut if the minifier was aware of which functionality in the module was required for the project that it's being minified for.
Let's say a project uses underscore.js, but only uses the exported functions _.isEmpty
and _.isArray
. Looking at the source, the minifier could j开发者_高级运维ust include _.isEmpty
, _.isArray
, _.isString
, and _.hasOwnProperty
.
Doing this would probably necessitate marking-up the module source to say what's what and to express intramodule dependencies, e.g.:
//{{ "_.isEmpty" depends "_.isArray", "_.isString", "_.hasOwnProperty"
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
return true;
};
//}}
One could then run minify underscore.js ["_.isEmpty", "_.isArray"]
to cut out everything not required. Alternatively, you could include the same tags in your code to express those required parts of underscore.js
, then bundle your code with underscore and condtionally compile the result. In both cases, you could then run the standard minifier at the end.
As described, this is not even JS-specific, so something must exist somewhere. A cleverer conditional-includer could perhaps analyse the code to detect dependencies, but this is a Hard Problem.
I'm looking for a JS "minifier" that cuts dead code, helped by dependency annotations. Does such a thing exist?
Google's Closure Compiler's "advanced compilation" functionality does what you want -- it parses your JavaScript source and automatically removes its dead code (try it online). A downside is that you may have to make changes to your code for it to work, though.
精彩评论