Reputation: 28154
In my JavaScript application, I use several objects for internal purposes only (the users don't need to access them). for example:
var images={
blank:"blank.gif",
plus:"plus.gif",
minus:"minus.gif"
}
When I use a minifier like Uglify.js, the property names (blank, plus, minus) are kept as is. Is there a way to minify them?
What I have considered so far:
Is there a better way?
Upvotes: 17
Views: 6910
Reputation: 11
[Update May 2020] The syntax for --mangle-props
appears to have has changed a little for gulp-uglify
. Instead of mangleProperties it's now a 'properties' object inside a 'mangle' object:
Here's my complete code taken from my gulpfile.js, which works as of May 2020:
uglify = require('gulp-uglify');
...
const uglifyOptions = {
mangle: {
properties: { regex: /^p1_/ }
}
}
...
.pipe( uglify( uglifyOptions ) )
Upvotes: 1
Reputation: 1919
If you uniquely prefix your internal properties, you can try --mangle-props regex
per https://github.com/mishoo/UglifyJS2.
Here's its use in my gulpfile which requires gulp-uglify.
var uglifyOpts = {
// Mangles the private "p1_" prefixed properties in an object
mangleProperties: {
regex: /^p1_/
}
};
Upvotes: 7
Reputation: 1140
Using an object allows the use of variables as properties. Wrapping it in a closure makes those variables worthy of minifying.
//Wrap in closure
(function() {
//Property Variables
var blank = 0;
var plus = 1;
var minus = 2;
//Define Object
var image = [];
image[blank] = "blank.gif";
image[plus] = "plus.gif";
image[minus] = "minus.gif";
//Accessors - must be within closure
image[blank]; //blank.gif
image[plus]; //plus.gif
image[minus]; //minus.gif
})();
To access the values above, the constants must be used within the closure.
If using Google's Closure Compiler, using var image = [];
will be more efficient in declaring the array since the property values are numbered from zero, i.e. 0
, 1
, 2
.
Otherwise, var image = {};
works well too.
Upvotes: 7
Reputation: 324760
Well, in this case, you could just replace all references to images.blank
with "blank.gif"
, same with plus
and minus
. While that does mean more work if you, for some reason, decide to change all your filenames, there's nothing a global search and replace can't fix. No need for the images
object at all.
Upvotes: -4