EzDevInfo.com

UglifyJS2

JavaScript parser / mangler / compressor / beautifier toolkit UglifyJS — JavaScript parser, compressor, minifier written in JS

Uglify with SourceMaps while using grunt usemin and rev

I want to log javascript errors to server but the stacktrace is not useful with minified JS code. So I was thinking of using either Getsentry or Rollbar which shows proper stack trace with the help of sourcemaps. But I'm struggling to create sourcemap in first place.

I'm getting this error

"Destination (_build/js/app.js) not written because src files were empty."

Once it creates source map properly, there will be another problem i.e. rev will rename the file. I also need to leave the unminified concatenated file.

Below is my gruntfile.js (I've removed few bits out of it.)

module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        clean: {
            jsFolders: {
                src: [
                    '_build/js/ui',
                    '_build/js/vendor',
                    '_build/js/app',
                    '_build/js/*templates.js'
                ]
            },
            build: {
                src: ['_build/**/*']
            }
        },

        copy: {
            build: {
                files: [{
                    expand: true,
                    src: [
                        'index.html',
                        'img/**/*', //includes web.cofig also.
                        'img/**/*.svg',
                        '!img/**/*.psd',
                        'js/**/*', //includes web.cofig also.
                        'css/**/*', //includes web.cofig also.
                        '*.png',
                        'favicon.ico'
                    ],
                    dest: '_build/'
                }]
            },
        },

        rev: {
            option: {
                algorithm: 'sha1',
                length: 4
            },
            all: {
                files: {
                    src: [
                        '_build/**/*.{js,css,eot,ttf,woff}'
                    ]
                }
            }
        },

        useminPrepare: {
            html: ['_build/index.html']
        },

        usemin: {
            html: [
                '_build/index.html'
            ],
            css: [
                '_build/css/**/*.css'
            ]
        },

        uglify: {
            options: {
                sourceMap: '_build/js/app.js.map',
            },
            js: {
                files: {
                    '_build/js/app.js': ['_build/js/app.js']
                }
            }
        },

        cssmin: {
            minify: {
                expand: true,
                cwd: '_build/css/',
                src: '*.css',
                dest: '_build/css/'
            }
        },
    });

grunt.registerTask('build', [
        'clean:build',
        'handlebars',
        'compass',
        'autoprefixer',
        'copy:build',
        'useminPrepare',
        'concat',
        'uglify',
        'cssmin',
        'clean:jsFolders',
        'rev',
        'usemin',
    ]);

};

UPDATE


Tried @Andy's solution, it still shows the same error "Destination (_build/js/app.js) not written because src files were empty." and it also says below while building

 uglify:
  { options:
   { sourceMap: true,
     sourceMapName: '_build/js/app.js.map' },
  js: { files: { '_build/js/app.js': [ '_build/js/app.js' ] } },
  generated:
   { files:
      [ { dest: 'dist\\js\\app.js',
          src: [ '.tmp\\concat\\js\\app.js' ] } ] } }

Don't know where it got dest name from. My output folder is _build.

UPDATE2:
Refer to below links for better solution
http://stackoverflow.com/a/20574196/148271 https://github.com/gruntjs/grunt-contrib-uglify/issues/39#issuecomment-14856100


Source: (StackOverflow)

Tell UglifyJS to skip a particular area of code

Is there a way to tell UglifyJS to skip a particular section of code, perhaps using comments like this:

// uglifyjs:skipStart
filter = function(item){ /* some crazy filter logic that will repeat 500,000 times */ }
// uglifyjs:skipEnd

My use case has to do with avoiding the minification of a function that will be inlined and parsed in a custom way for performance gain. Minification breaks the simplified parser.


Source: (StackOverflow)

Advertisements

How to run UglifyJS2 without Node.JS

Anyway to run UglifyJS2 without node.js? Say I would like to run it in a JVM process using JavaScript script engine. How to do that?


Source: (StackOverflow)

Uglify: generate source map but don't append sourceMappingURL comment

I am using UglifyJS2 to minify javascript source code.

I would like to generate source maps and point to those source maps using the X-SourceMap HTTP header, instead of the //# sourceMappingURL comment.

So, is there a facility to generate a sourcemap in uglify without appending the sourceMappingURL comment, short of just pulling it out myself?


Source: (StackOverflow)

How to parse and iterate prototype methods with Uglify.js?

I 'd like to parse some JavasScript code to list all methods for a given "class" using uglify js 2. In my case the TreeWalker returns a node with name : null and there is no information that allow conclusions to parent.

Does anyone know a different approach? I expected something like name : "Test.method_name"
So far I tryied the folowing...

parsetests.js

var UglifyJS = require("uglify-js2");
var util = require("util");
var code = require("fs").readFileSync("test.js").toString();
var toplevel = UglifyJS.parse(code);
var log = function(obj, depth) {
    console.log(util.inspect(obj, showHidden=false, depth, colorize=true));
};
var toplevel = UglifyJS.parse(code);
var walker = new UglifyJS.TreeWalker(function(node){
    if (node instanceof UglifyJS.AST_Function ) {
        log(node, 2);        
    }
});
toplevel.walk(walker);

test.js

function Test(argument1) {
    var m = argument1 + "test";
    return this;
}


Test.prototype.method_name = function(first_argument) {
    // body...
    return "a";
};

UglifyJS.TreeWalker node:

{ end:
   { file: null,
     comments_before: [],
     nlb: true,
     endpos: 156,
     pos: 155,
     col: 0,
     line: 10,
     value: '}',
     type: 'punc' },
  start:
   { file: null,
     comments_before: [],
     nlb: false,
     endpos: 111,
     pos: 103,
     col: 29,
     line: 7,
     value: 'function',
     type: 'keyword' },
  body:
   [ { end: [Object],
       start: [Object],
       value: [Object] } ],
  cname: undefined,
  enclosed: undefined,
  parent_scope: undefined,
  uses_eval: undefined,
  uses_with: undefined,
  functions: undefined,
  variables: undefined,
  directives: undefined,
  uses_arguments: undefined,
  argnames:
   [ { end: [Object],
       start: [Object],
       thedef: undefined,
       name: 'first_argument',
       scope: undefined,
       init: undefined } ],
  name: null }

Source: (StackOverflow)

Can uglify-js remove the console.log statements?

I'm using uglify-js to minify the source code. I want to remove the console.log statements of the original source code. Is it possible? Or is there any other compressor tool supports this?

I use the code as below in Node.js.

var uglify = require('uglify-js');
var originalSourceCode = 'var name = function(){var str = "test"; return str}; console.log("log data");';
var minifiedCode = uglify.minify(originalSourceCode, {
                fromString : true,
                mangle: {},
                warnings: true
            });
console.log(minifiedCode);

The output is:

$node m.js
{ code: 'var name=function(){var a="test";return a};console.log("log data");',
  map: 'null' }

In the minified code the console.log isn't removed.


Source: (StackOverflow)

Source maps with grunt

Do you know of a workflow that includes source maps for an app compiled with grunt?

I am well aware of plugins like uglifyjs that allow you to simply generate a source map. But I'm looking for incorporating this into a more complex workflow, rather than just making a one-off source map.

I've noticed that the most popular Yeoman generators (that I know of) are missing source maps in their workflows. Is this just because of a lack of support in the major plugins for source maps? Or is it instead that source maps aren't necessary in work flows, and I just can't think of a clever enough alternative?

Notable sources of trouble with popular grunt plugins that I've run into include:

uglify being unable to handle even the most basic of project structures without a hacky fix.

usemin also being unable to handle source maps beyond the simplest of configurations, in that it can really only support one per project (but still requires a hack to correct it). A possible solution is obviously to stop using usemin altogether, but then you lose out on all of the benefits of it, like pairing it with rev, watch, and connect.

I'm thinking that my best course of action might be testing with un-concatenated/not-minified sources when I'm testing my app. This is, of course, less than ideal, as I'd like my test environment to mirror the production one as best as possible.

Do you use source maps in your grunt project? How do you do it? If not, how do you get around the lack of support for them?


Source: (StackOverflow)

UglifyJS property mangling

According to the docs, UglifyJS can mangle all property names except those on a provided reserved list. Is it possible to do it the other way, so only properties on provided list will be mangled?

If so, what options do I need to pass to uglify.minify(files, { ... })?


Source: (StackOverflow)

Specifying Whitespace Only option for UglifyJS2

I am trying to use grunt for minifying javascript files in a project using UglifyJS2.

Does UglifyJS2 have any options like WHITESPACE_ONLY ( which exists in Closure Compiler)?

What are the values do I have to pass in options node in GruntFile.js for that effect?

uglify: {
        options: {
            mangle: { toplevel: false },
            squeeze: { dead_code: false }
        },
        'dist': {
            src: '**/*.js',
            dest: '**/*.js'
        }
    }

Source: (StackOverflow)

JavaScript source map keep function names

I installed UglifyJS2 in my ASP MVC 4 Project in Visual Studio as command line tool and used it to uglify a js file i wrote. I need to keep the function names as they are so i set --keep-fnames. So far so good after i tried the following command i got my uglified file containing the function names: uglifyjs sample.js --compress --mangle --keep-fnames --output sample.min.js

But as soo as i edited the uncompressed file i recognized that there was a so called source map which automatically compresses the new version to the .min.js file.

I want to use this source map but the problem is it doesnt keep my function names of the original javascript file and i found no solution to set the compression options anywhere in this source map file, neither i found any soultion in the web...

EDIT

After a little bit of research i found out that the source map comes from an extension for visual studio (webessentials 2012). Still i did not found any documentation about how to config the source map (if it is even possible).


Source: (StackOverflow)

Speed up Javascript uglification in Play 2.3.x build for external Webjar sources

I'm using Play framework 2.3.6 and Webjars for web lib dependencies. That is, my build.sbt contains something like "org.webjars" % "angularjs" % "1.2.26". To uglify my Javascript sources I added pipelineStages := Seq(rjs, uglify, digest, gzip) to my build.sbt.

Now, when running Play's 'stage' or 'dist' tasks it looks like all Javascript files getting uglified, that is, also files from the Webjar libraries.
[info] Uglify2 file: /target/web/rjs/build/lib/angularjs/angular.js

I would have expected that sources from the external Webjar libraries are left untouched as there already is a minified version. One problem with that is that the uglify process takes way too long. How can I speed up the uglification process?


Source: (StackOverflow)

Pound Sign (#) As Comment Start In JavaScript?

Does the pound sign (#) start a comment in JavaScript? I have a website I am using with NPM and when I tried to minify the JavaScript with Grunt, Uglify threw the error:

Warning: Uglification failed.
Unexpected character '#'.
Line 1 in app/min-libs/node_modules/grunt-contrib-jshint/node_modules/jshint/nod
e_modules/cli/examples/cat.js
 Use --force to continue.

The file name being referred to seems to be from another NPM module, meaning they know what they are doing. So when I went to app/min-libs/node_modules/grunt-contrib-jshint/node_modules/jshint/node_modules/cli/examples/cat.js, the offending line says:

#!/usr/bin/env node

Is this a comment or do the owners of this NPM module know some super-secret forbidden JavaScript technique?


Source: (StackOverflow)

How to uglify JavaScript using UglifyJS 2?

I tried to uglify a simple javascript file using UglifyJS2.

Here are the contents of the file :

//this is simply a sample var
var sampleVar = "xyz";

//lots of comments
//this is just another comment
//such things should not be present in javascript
//waiting to see result after uglifying

//this is simply a sample function
function sampleFunction()
{
  var sampleLocalVar = "xzx";
  if(true)
  {
    //inserting some sample comments
    alert("in if block");
  }
  else
  {
    //inserting some sample comments
    alert("in else block");
  }
}

Here's the command that I'm using to uglify:

uglifyjs -c -m sample.js sample.min.js

Error that I'm receiving :

Dot
Error parsing arguments in : sample.js

Source: (StackOverflow)

Does UglifyJS2 support base64-encoded in-source-maps?

I'm using UglifyJS2 to compress an output file from Browserify. Browserify has generated its own source map which it tacks the bottom of the file like so:

//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjo...

I've got an error my JS somewhere in one of the files I've require'd, but Chrome is telling me the error occurred somewhere in the browserify output file rather than pointing me all the way back to require'd file.

The in-source-map option doesn't say anything about base64-encodings, so I haven't set it to anything.


Source: (StackOverflow)

Batch File Exits After Running One Node Application Script

I need to run several UglifyJS2 scripts with Node. I've added the command I want to run to a bat file and it runs OK.

When I add a second command, like "cd ..", the command isn't executed! Very confusing.

cd go somewhere
uglifyjs ..\somescript -o ..\somefile.min.js --source-map ..\somemap.js.map --screw-ie8 
cd ..

I'd like to be able to run several different scripts from the same bat file.

uglifyjs ..\somescript1 -o ..\somefile1.min.js
uglifyjs ..\somescript2 -o ..\somefile2.min.js
uglifyjs ..\somescript3 -o ..\somefile3.min.js

I'm not sure whether this is an issue in Node, Uglify, or expected behavior.


Source: (StackOverflow)