Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
grunt-contrib-uglify
Advanced tools
The grunt-contrib-uglify package is a Grunt plugin that provides the ability to minify JavaScript files using UglifyJS. It helps in reducing the file size of JavaScript files by removing unnecessary characters, comments, and whitespace, which can improve the performance of web applications.
Minify JavaScript files
This feature allows you to minify multiple JavaScript files into a single output file. The code sample demonstrates how to configure the grunt-contrib-uglify task to take two input files (input1.js and input2.js) and produce a minified output file (output.min.js).
{
"uglify": {
"my_target": {
"files": {
"dest/output.min.js": ["src/input1.js", "src/input2.js"]
}
}
}
}
Generate source maps
This feature allows you to generate source maps for the minified JavaScript files. Source maps help in debugging by mapping the minified code back to the original source code. The code sample shows how to configure the grunt-contrib-uglify task to generate a source map file (output.map) along with the minified output file (output.min.js).
{
"uglify": {
"my_target": {
"options": {
"sourceMap": true,
"sourceMapName": "dest/output.map"
},
"files": {
"dest/output.min.js": ["src/input1.js", "src/input2.js"]
}
}
}
}
Customize UglifyJS options
This feature allows you to customize the UglifyJS options for the minification process. The code sample demonstrates how to configure the grunt-contrib-uglify task to disable variable name mangling and remove console statements from the output file (output.min.js).
{
"uglify": {
"my_target": {
"options": {
"mangle": false,
"compress": {
"drop_console": true
}
},
"files": {
"dest/output.min.js": ["src/input1.js", "src/input2.js"]
}
}
}
}
UglifyJS is a JavaScript parser, minifier, compressor, and beautifier toolkit. It is the underlying library used by grunt-contrib-uglify. While grunt-contrib-uglify is a Grunt plugin, uglify-js can be used directly in Node.js scripts or other build tools for more fine-grained control over the minification process.
Terser is a JavaScript parser and mangler/compressor toolkit for ES6+. It is a fork of UglifyJS that aims to support modern JavaScript syntax. Terser can be used as an alternative to UglifyJS for projects that use ES6+ features. It can be integrated with various build tools, including Grunt, via plugins like grunt-terser.
Babel Minify (also known as babel-preset-minify) is a minifier based on the Babel toolchain. It provides a set of Babel plugins that perform code transformations to reduce the size of JavaScript files. Babel Minify is particularly useful for projects that already use Babel for transpiling ES6+ code to ES5.
Minify JavaScript files with UglifyJS
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-contrib-uglify --save-dev
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt.loadNpmTasks('grunt-contrib-uglify');
Run this task with the grunt uglify
command.
Task targets, files and options may be specified according to the grunt Configuring tasks guide.
This task primarily delegates to UglifyJS, so please consider their documentation as required reading for advanced configuration.
2.x
Option | Replacement |
---|---|
ASCIIOnly | output.ascii_only |
enclose | — |
exportAll | — |
expression | parse.expression |
indentLevel | output.indent_level |
mangleProperties | mangle.properties |
maxLineLen | output.max_line_len |
preserveComments | output.comments |
quoteStyle | output.quote_style |
screwIE8 | !ie8 |
sourceMapIncludeSources | sourceMap.includeSources |
sourceMapRoot | sourceMap.root |
sourceMapUrl | sourceMap.url |
Type: Boolean
Object
Default: {}
Turn on or off mangling with default options. If an Object
is specified, it is passed directly to ast.mangle_names()
and ast.compute_char_frequency()
(mimicking command line behavior). View all options here.
Type: Boolean
Object
Default: {}
Turn on or off source compression with default options. If an Object
is specified, it is passed as options to UglifyJS.Compressor()
. View all options here.
Type: Boolean
Object
Default: false
Turns on beautification of the generated source code. View all options here
Type: Boolean
Default: false
Parse a single expression, rather than a program (for parsing JSON)
Type: string
Choices: 'min'
, 'gzip'
Default: 'min'
Report minification result or both minification and gzip results.
This is useful to see exactly how well uglify-js is performing but using 'gzip'
will make the task take 5-10x longer to complete. Example output.
Type: Boolean
Default: false
If true
, a source map file will be generated in the same directory as the dest
file. By default it will have the same basename as the dest
file, but with a .map
extension.
Type: String
Function
Default: undefined
To customize the name or location of the generated source map, pass a string to indicate where to write the source map to. If a function is provided, the uglify destination is passed as the argument and the return value will be used as the file name.
Type: String
Function
Default: undefined
The location of an input source map from an earlier compilation, e.g. from CoffeeScript. If a function is provided, the uglify source is passed as the argument and the return value will be used as the sourceMap name. This only makes sense when there's one source file.
Type: Boolean
Default: false
Pass this flag if you want to include the content of source files in the source map as sourcesContent property.
Type: String
Default: undefined
With this option you can customize root URL that browser will use when looking for sources.
If the sources are not absolute URLs after prepending of the sourceMap.root
, the sources are resolved relative to the source map.
Type: String
Default: undefined
Override the calculated value for sourceMappingURL
in the source map. This is useful if the source map location is not relative to the base path of the minified file, i.e. when using a CDN
Type: String
Default: undefined
Wrap all of the code in a closure, an easy way to make sure nothing is leaking.
For variables that need to be public exports
and global
variables are made available.
The value of wrap is the global variable exports will be available as.
Type: Boolean
Default: false
Enables to encode non-ASCII characters as \uXXXX.
Type: Boolean
String
Function
Default: undefined
Options: false
'all'
'some'
Turn on preservation of comments.
false
will strip all comments'all'
will preserve all comments in code blocks that have not been squashed or dropped'some'
will preserve all comments that include a closure compiler style directive (@preserve
@license
@cc_on
)Function
specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true
or false
RegExp
'/[RegExp]/'
will preserve comments matching given RegExp or stringified RegExpType: String
Default: ''
This string will be prepended to the minified output. Template strings (e.g. <%= config.value %>
will be expanded automatically.
Type: String
Default: ''
This string will be appended to the minified output. Template strings (e.g. <%= config.value %>
will be expanded automatically.
Type: Boolean
Default: false
Set this to true
if you still care about full compliance with Internet Explorer 6-8 quirks.
Type: Boolean
Object
Default: false
Turn on or off property mangling with default options. If an Object
is specified, it is passed directly to ast.mangle_properties()
(mimicking command line behavior). View all options here.
Type: Boolean
Default: false
Use this flag in conjunction with mangle.properties
to prevent built-in browser object properties from being mangled.
Type: Array
Default: []
Use this with mangle.properties
to pass one or more JSON files containing a list of variables and object properties
that should not be mangled. See the UglifyJS docs for more info on the file syntax.
Type: String
Default: ''
A string that is a path to a JSON cache file that uglify will create and use to coordinate symbol mangling between
multiple runs of uglify. Note: this generated file uses the same JSON format as the exceptionsFiles
files.
Type: Integer
Default: 0
Preserve or enforce quotation mark style.
0
will use single or double quotes such as to minimize the number of bytes (prefers double quotes when both will do)1
will always use single quotes2
will always use double quotes3
will preserve original quotation marksThis configuration will compress and mangle the input files using the default options.
// Project configuration.
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input1.js', 'src/input2.js']
}
}
}
});
Specify mangle: false
to prevent changes to your variable and function names.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
mangle: false
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
You can specify identifiers to leave untouched with an reserved
array in the mangle
options.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
mangle: {
reserved: ['jQuery', 'Backbone']
}
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
Generate a source map by setting the sourceMap
option to true
. The generated
source map will be in the same directory as the destination file. Its name will be
the basename of the destination file with a .map
extension. Override these
defaults with the sourceMapName
attribute.
// Project configuration.
grunt.initConfig({
uglify: {
my_target: {
options: {
sourceMap: true,
sourceMapName: 'path/to/sourcemap.map'
},
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
Set the sourceMap.includeSources
option to true
to embed your sources directly into the map. To include
a source map from a previous compilation pass it as the value of the sourceMapIn
option.
// Project configuration.
grunt.initConfig({
uglify: {
my_target: {
options: {
sourceMap: {
includeSources: true
},
sourceMapIn: 'example/coffeescript-sourcemap.js', // input sourcemap from a previous compilation
},
files: {
'dest/output.min.js': ['src/input.js'],
},
},
},
});
Refer to the UglifyJS SourceMap Documentation for more information.
Specify drop_console: true
as part of the compress
options to discard calls to console.*
functions.
This will suppress warning messages in the console.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
compress: {
drop_console: true
}
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
Specify beautify: true
to beautify your code for debugging/troubleshooting purposes.
Pass an object to manually configure any other output options.
See UglifyJS documentation for more information.
// Project configuration.
grunt.initConfig({
uglify: {
my_target: {
options: {
beautify: true
},
files: {
'dest/output.min.js': ['src/input.js']
}
},
my_advanced_target: {
options: {
beautify: {
width: 80
}
},
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
In this example, running grunt uglify:my_target
will prepend a banner created by interpolating the banner
template string with the config object. Here, those properties are the values imported from the package.json
file (which are available via the pkg
config property) plus today's date.
Note: you don't have to use an external JSON file. It's also valid to create the pkg
object inline in the config. That being said, if you already have a JSON file, you might as well reference it.
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
You can also enable UglifyJS conditional compilation. This is commonly used to remove debug code blocks for production builds. This is equivalent to the command line --define
option.
See UglifyJS global definitions documentation for more information.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
compress: {
global_defs: {
'DEBUG': false
},
dead_code: true
}
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
This configuration will compress and mangle the files dynamically.
// Project configuration.
grunt.initConfig({
uglify: {
my_target: {
files: [{
expand: true,
cwd: 'src/js',
src: '**/*.js',
dest: 'dest/js'
}]
}
}
});
This configuration will compress and mangle all js files separately in each folder.
Also exclude jQuery for mangling and ignore all *.min.js
files.
// Project configuration.
uglify: {
dev: {
options: {
mangle: {
reserved: ['jQuery']
}
},
files: [{
expand: true,
src: ['dist/assets/js/*.js', '!dist/assets/js/*.min.js'],
dest: 'dist/assets',
cwd: '.',
rename: function (dst, src) {
// To keep the source js files and make new files as `*.min.js`:
// return dst + '/' + src.replace('.js', '.min.js');
// Or to override to src:
return src;
}
}]
}
},
This configuration will turn on object property name mangling, but not mangle built-in browser object properties.
Additionally, variables and object properties listed in the myExceptionsFile.json
will be mangled. For more info,
on the format of the exception file format please see the UglifyJS docs.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
mangle: {
properties: true
},
reserveDOMCache: true,
exceptionsFiles: [ 'myExceptionsFile.json' ]
},
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});
Turn on use of name mangling cache to coordinate mangled symbols between outputted uglify files. uglify will the
generate a JSON cache file with the name provided in the options. Note: this generated file uses the same JSON format
as the exceptionsFiles
files.
// Project configuration.
grunt.initConfig({
uglify: {
options: {
nameCache: '.tmp/grunt-uglify-cache.json',
},
my_target: {
files: {
'dest/output1.min.js': ['src/input1.js'],
'dest/output2.min.js': ['src/input2.js']
}
}
}
});
object.assign
.screwIE8
is enabled by default.beautify
when passed as an object. Fix docs about report
values.global-defs
and --define
options. Add sourceMapUrl
option. Add bare_returns
option. Optionally set report verbosity level using report option.mangle
options.screwIE8
option. Fix issue with explicit compress
in Node.js 0.12.0.sourceMapRoot
options. Update readme descriptions. Remove reference to clean-css.ASCIIOnly
option. Other fixes.grunt.template.process
.sourceMapIncludeSources
option.sourceMap
option not set, addresses #109.footer
option.sourcemappingUrl
syntax #56. Disable sorting of names for consistent mangling #44. Update docs for sourceMapRoot
#47 #25.report
option.this.files
API.Task submitted by "Cowboy" Ben Alman
This file was generated on Mon Sep 11 2017 13:21:40.
FAQs
Minify JavaScript files with UglifyJS
The npm package grunt-contrib-uglify receives a total of 113,232 weekly downloads. As such, grunt-contrib-uglify popularity was classified as popular.
We found that grunt-contrib-uglify demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 9 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.