Ejemplo n.º 1
0
function minify(string) {
  return uglify.minify(string, {fromString: true}).code;
}
Ejemplo n.º 2
0
 afterHook: function (source) {
   source = ngmin.annotate(source);
   source = uglify.minify(source, { fromString: true }).code;
   return source;
 }
Ejemplo n.º 3
0
  return function(err, results) {
    if (err) throwError(err);
    var expires  = new Date(new Date().getTime() + (31556926 * 1000)).toUTCString();
    var headers = {
        'Set-Cookie'                : ''
      , 'response-content-type'     : type
      , 'Content-Type'              : type
      , 'response-cache-control'    : 'maxage=31556926'
      , 'Cache-Control'             : 'maxage=31556926'
      , 'response-expires'          : expires
      , 'Expires'                   : expires
      , 'response-content-encoding' : 'gzip'
      , 'Content-Encoding'          : 'gzip'
      , 'x-amz-acl'                 : 'public-read'
    };
    switch(method) {
      case 'uglify':
        if (results instanceof Array) results = results.join("\n");
        var final_code = uglify.minify(results,{
            fromString: true
          , output : { comments : '/license/' } 
        }).code;
        zlib.gzip(final_code, function(err, buffer) {
          if (err) throwError(err);
          S3.putBuffer(buffer, fileName, headers, function(err, response) {
            if (err) return throwError(err);
            if (response.statusCode !== 200) {
              //return throwError('unsuccessful upload of script "' + fileName + '" to S3');
              console.log('unsuccessful upload of script "' + fileName + '" to S3');
              return finishUpload();
            } else {
              logger({ task: 'express-cdn', message: 'successfully uploaded script "' + fileName + '" to S3' });
              return finishUpload();
            }
          });
        });
        break;
      case 'minify':
        if (!(results instanceof Array)) { results = [results]; assets = [assets] }
        var final_code = [];
        // NOTE: Added back in clean CSS, looks like its a bit less bad at minifcation now

        for (var key in results) {
          var minify = new cleanCSS().minify(results[key]);
          var assetPath  = assets[key];
          var assetBasePath = path.dirname(assetPath);
          var fileBasePath  = path.dirname(path.join(options.publicDir, fileName));

          // Process images
          minify = minify.replace(/(?:background\-image|background|content|border\-image)\:[^;\n]*\)/g, function (rootMatch) {

            //Multiples Images URL per background
            return rootMatch.replace(/url\((?!data:)['"]?([^\)'"]+)['"]?\)/g, function (match, url) {

              if (options.production) {
                var relativePath = url;
                if ('/' === relativePath[0]) {
                  relativePath = path.join(options.publicDir, relativePath.substr(1));
                }
                else {
                  relativePath = path.join(assetBasePath, relativePath);
                }
                var imageResource = compile(relativePath.substr(options.publicDir.length + 1), relativePath, S3, options, 'image', 'image/'+path.extname(url).substr(1), Date.now(), null, null)();
                return 'url('+path.relative(fileBasePath, relativePath)+')';
              } else {
                return 'url('+url+')';
              }
            });
          });

          // Process fonts
          minify = minify.replace(/(?:src)\:[^;]*\)/g, function (rootMatch) {

            //Multiples Fonts URL per SRC
            return rootMatch.replace(/url\((?!data:)['"]?([^\)'"]+)['"]?\)/g, function (match, url) {

              if (options.production) {
                var relativePath = url;
                if ('/' === relativePath[0]) {
                  relativePath = path.join(options.publicDir, relativePath.substr(1));
                }
                else {
                  relativePath = path.join(assetBasePath, relativePath);
                }
                var mimeType = mime.lookup(relativePath);
                var fontResource = compile(relativePath.substr(options.publicDir.length + 1), relativePath, S3, options, 'font', mimeType, Date.now(), null, null)();
                return 'url('+path.relative(fileBasePath, relativePath)+')';
              } else {
                return 'url('+url+')';
              }
            });
          });

          final_code.push(minify);
        }

        zlib.gzip(final_code.join("\n"), function(err, buffer) {
          if (err) throwError(err);
          S3.putBuffer(buffer, fileName, headers, function(err, response) {
            if (err) throwError(err);
            if (response.statusCode !== 200) {
              //throwError('unsuccessful upload of stylesheet "' + fileName + '" to S3');
              console.log('unsuccessful upload of stylesheet "' + fileName + '" to S3');
              return finishUpload();
            } else {
              logger({ task: 'express-cdn', message: 'successfully uploaded stylesheet "' + fileName + '" to S3' });
              return finishUpload();
            }
          });
        });

        break;
      case 'optipng':
        var img = assets;
        var optipng = spawn(optipngPath, [img]);
        optipng.stdout.on('data', function(data) {
          logger({ task: 'express-cdn', message: 'optipng: ' + data });
        });
        optipng.stderr.on('data', function(data) {
          logger({ task: 'express-cdn', message: 'optipng: ' + data });
        });
        optipng.on('exit', function(code) {
          // OptiPNG returns 1 if an error occurs
          if (code !== 0)
            throwError('optipng returned an error during processing \'' + img + '\': ' + code);

          logger({ task: 'express-cdn', message: 'optipng exited with code ' + code });
          fs.readFile(img, function(err, data) {
            zlib.gzip(data, function(err, buffer) {
              S3.putBuffer(buffer, fileName, headers, function(err, response) {
                if (err) throwError(err);
                if (response.statusCode !== 200) {
                  //throwError('unsuccessful upload of image "' + fileName + '" to S3');
                  console.log('unsuccessful upload of image "' + fileName + '" to S3');
                  return finishUpload();
                } else {
                  logger({ task: 'express-cdn', message: 'successfully uploaded image "' + fileName + '" to S3' });
                  // Hack to preserve original timestamp for view helper
                  fs.utimesSync(img, new Date(timestamp), new Date(timestamp));
                  return finishUpload();
                }
              });
            });
          });
        });
        break;
      case 'jpegtran':
        var jpg = assets;
        var jpegtran = spawn(jpegtranPath, [ '-copy', 'none', '-optimize', '-outfile', jpg, jpg ]);
        jpegtran.stdout.on('data', function(data) {
          logger({ task: 'express-cdn', message: 'jpegtran: ' + data });
        });
        jpegtran.stderr.on('data', function(data) {
          throwError(data);
        });
        jpegtran.on('exit', function(code) {
          logger({ task: 'express-cdn', message: 'jpegtran exited with code ' + code });
          fs.readFile(jpg, function(err, data) {
            zlib.gzip(data, function(err, buffer) {
              S3.putBuffer(buffer, fileName, headers, function(err, response) {
                if (err) throwError(err);
                if (response.statusCode !== 200) {
                  //throwError('unsuccessful upload of image "' + fileName + '" to S3');
                  console.log('unsuccessful upload of image "' + fileName + '" to S3');
                  return finishUpload();
                } else {
                  logger({ task: 'express-cdn', message: 'successfully uploaded image "' + fileName + '" to S3' });
                  // Hack to preserve original timestamp for view helper
                  fs.utimesSync(jpg, new Date(timestamp), new Date(timestamp));
                  return finishUpload();
                }
              });
            });
          });
        });
        break;
      case 'image':
      case 'font':
        var image = assets.split("?")[0].split("#")[0];
        fileName  = fileName.split("?")[0].split("#")[0];
        fs.readFile(image, function(err, data) {
          zlib.gzip(data, function(err, buffer) {
            S3.putBuffer(buffer, fileName, headers, function(err, response) {
              if (err) throwError(err);
              if (response.statusCode !== 200) {
                //throwError('unsuccessful upload of image "' + fileName + '" to S3');
                console.log('unsuccessful upload of image "' + fileName + '" to S3');
                return finishUpload();
              } else {
                logger('successfully uploaded image "' + fileName + '" to S3');
                // Hack to preserve original timestamp for view helper
                try {
                  fs.utimesSync(image, new Date(timestamp), new Date(timestamp));
                  return finishUpload();
                } catch (e) {
                  return finishUpload();
                }
              }
            });
          });
        });
        break;
    }
  };
Ejemplo n.º 4
0
      _.forEach(bundleKeys, function(bundleKey) {

          var items = _.where(jsAssets, {bundleKey: bundleKey});

          if(items.length === 0) { return; }

          var compiled, serviceName, buildNumber, tag, externalBuild;

          bosco.log('Compiling ' + _.size(items) + ' ' + bundleKey.blue + ' JS assets ...');

          var uglifyConfig = bosco.config.get('js:uglify');

          if(!serviceName) {
            var firstItem = items[0];
            serviceName = firstItem.serviceName;
            buildNumber = firstItem.buildNumber;
            tag = firstItem.tag;
            externalBuild = firstItem.externalBuild;
          }

          var uglifyOptions = {
            output: uglifyConfig ? uglifyConfig.outputOptions : null,
            compressor: uglifyConfig ? uglifyConfig.compressorOptions : null,
            mangle: uglifyConfig ? uglifyConfig.mangle : null,
                outSourceMap: tag + '.js.map',
                sourceMapIncludeSources: true
            };

          try {
            compiled = UglifyJS.minify(_.values(_.pluck(items,'path')), uglifyOptions);
          } catch (ex) {
              bosco.error('There was an error minifying files in ' + bundleKey.blue + ', error:');
              console.log(ex.message + '\n');
              compiled = {
                  code: ''
              };
          }


          var mapKey = createKey(serviceName, buildNumber, tag, 'js', 'js', 'map');

          var mapItem = {};
          mapItem.assetKey = mapKey;
          mapItem.serviceName = serviceName;
          mapItem.buildNumber = buildNumber;
          mapItem.path = 'js-source-map';
          mapItem.relativePath = 'js-source-map';
          mapItem.extname = '.map';
          mapItem.tag = tag;
          mapItem.type = 'js';
          mapItem.mimeType = 'application/javascript';
          mapItem.content = compiled.map;
          staticAssets.push(mapItem);

          var minifiedKey = createKey(serviceName, buildNumber, tag, null, 'js', 'js');
          var minifiedItem = {};
          minifiedItem.assetKey = minifiedKey;
          minifiedItem.serviceName = serviceName;
          minifiedItem.buildNumber = buildNumber;
          minifiedItem.path = 'minified-js';
          minifiedItem.relativePath = 'minified-js';
          minifiedItem.extname = '.js';
          minifiedItem.tag = tag;
          minifiedItem.type = 'js';
          minifiedItem.mimeType = 'application/javascript';
          minifiedItem.content = compiled.code;
          staticAssets.push(minifiedItem);

      });
Ejemplo n.º 5
0
        config.components.forEach((component) => {
            console.log("Bundling component: ", component.name);
            console.log("----------------------------------------------------------------------");
            // Read the styles file: component.css
            let cssExtension = path.extname(component.css.fileName);
            let rawCss = fs.readFileSync(component.css.fileName,'utf8');
            let css = rawCss;
            // CSS Preprocessing
            switch(cssExtension) {
                case ".scss":
                case ".sass":
                    // sass files
                    const sass = require("node-sass");
                    let result = sass.renderSync({
                        data: rawCss.toString(),
                        outputStyle: (component.css.compress) ? "compressed" : "nested",
                        includePaths: [path.dirname(component.css.fileName)]
                    });
                    css = result.css;
                    break;
                case ".less":
                    const less = require("less");
                    let lessOptions = { compress: false};
                    lessOptions.compress = (component.css.compress) ? true : false;
                    less.render(rawCss.toString(),lessOptions,function(err,output) {
                        if(err) {
                            console.log(err);
                        }
                        css = output.css;
                    });
                    break;
                case ".styl":
                    const stylus = require("stylus");
                    stylus.render(rawCss.toString(),{ compress: component.css.compress},function(err,output) {
                        if(err) {
                            console.log(err);
                        }
                        css = output;
                    });
                    break;
                default:
            }
            console.log("CSS file processed.");


            // Read the template file: component.html
            let htmlExtension = path.extname(component.html);
            
            let rawHtml = fs.readFileSync(component.html,'utf8');
            let html = rawHtml;
            // HTML Preprocessing
            switch(htmlExtension) {
                case ".jade":
                    const jade = require("jade");
                    html = jade.render(rawHtml.toString());
                    break;
                case ".ejs":
                    const ejs = require("ejs");
                    html = ejs.render(rawHtml.toString());
                    break;
                case ".haml":
                    const hamljs= require("hamljs");
                    html = hamljs.render(rawHtml.toString());
                    console.log(html);
                    break;
                default:
                    break;
            }
            console.log("HTML file processed.");

            // Read the script file: component.js
            let js = fs.readFileSync(component.js.fileName,'utf8');
            if(component.es6) {
                const babel = require("babel-core");
                let script = babel.transformFileSync(component.js.fileName);
                js = script.code;
            }
            // check for compress option
            if(component.js.compress) {
                const uglifyJS = require("uglify-js");
                var compressedJS = uglifyJS.minify(component.js.fileName,{ mangle: false});
                js = compressedJS.code;
            }

            console.log("JS file processed.");

            // Parse imports
            let htmlImports = "";
            component.imports.forEach((imp) => htmlImports += `<link rel='import' href='${imp}.html'>\n` );

            // Parse the template of css and html
            let template = `<template id="${component.name}">
                    <style>
                        ${css}
                    </style>
                    ${html}
                </template>
                <script>
                    ${js}
                </script>`;

            template = htmlImports + template;

            let fileName = component.name + ".html";
            fs.writeFileSync(fileName,template,'utf8');

            //console.log(template);
        });
Ejemplo n.º 6
0
      console.log(err);
    else
      console.log('Uploaded css/style.css');
  });
});


// Compress JS - Write to ./output/js/
console.log("Build JS");

var jsInput = [
  "./public/js/vendor.js",
  "./public/js/app.js"
];

var js = uglify.minify(jsInput, {outSourceMap: 'app.js.map'});

console.log("Upload JS to s3");

zlib.gzip(js.code, function(err, result) {
  if (err)
    throw err;
  s3bucket.putObject({
    ACL: 'public-read',
    Body: result,
    Key: prefix + 'js/app.' + version + '.js',
    ContentEncoding: 'gzip',
    ContentType: 'application/javascript'
  }, function(err) {
    if (err)
      console.log(err);
Ejemplo n.º 7
0
var fs = require("fs");
var UglifyJS = require("uglify-js");
var util = require("util");
var packageJson = require("./package.json");

var distInFile = "./dist/timezonecomplete.js";
var distOutFileVersioned = util.format("./temp/timezonecomplete.%s.min.js", packageJson.version);
var distOutFileUnversioned = "./dist/timezonecomplete.min.js";

var result = UglifyJS.minify(fs.readFileSync(distInFile, "utf-8"), { mangle: false });
if (result.error) {
	throw result.error;
}
fs.writeFileSync(distOutFileVersioned, result.code, { encoding: "utf-8"});
fs.writeFileSync(distOutFileUnversioned, result.code, { encoding: "utf-8"});
Ejemplo n.º 8
0
 error = Util.exec.try(function() {
     dataOptimized = uglify.minify(data, {fromString: true}).code;
 });
Ejemplo n.º 9
0
                var run = function () {

                    var javascript = data.toString();

                    if (file.config.uglify) {

                        try {

                            javascript = ugly.minify(javascript, {fromString: true, mangle: file.config.mangle}).code;

                        } catch (e) {

                            throw {message: 'Error on line ' + e.line + ' col ' + e.col + ' ' + e.message + ' of ' + file.input};
                        }
                    }

                    var importReg = {
                        append: /\/\/(?:\s|)@(?:prepros|codekit)-append\s+(.*)/gi,
                        prepend: /\/\/(?:\s|)@(?:prepros|codekit)-prepend\s+(.*)/gi
                    };

                    var read = function (filePathToRead) {

                        var importedFiles = {
                            append: [],
                            prepend: []
                        };

                        var regs = Object.keys(importReg);

                        _.each(regs, function (reg) {

                            var result;

                            while ((result = importReg[reg].exec(fs.readFileSync(filePathToRead))) !== null) {

                                var importedFile;

                                result[1] = result[1].replace(/'|"/gi, '').trim();

                                //Check if path is full or just relative
                                if (result[1].indexOf(':') >= 0) {

                                    importedFile = path.normalize(result[1]);

                                } else {

                                    importedFile = path.join(path.dirname(filePathToRead), result[1]);
                                }

                                //Check if file exists
                                if (fs.existsSync(importedFile)) {

                                    importedFiles[reg].push(importedFile);

                                } else {

                                    throw {message: 'Imported file "' + importedFile + '" not found \n Imported by "' + file.input + '"'};
                                }
                            }
                        });

                        return {
                            append: importedFiles.append,
                            prepend: importedFiles.prepend.reverse()
                        };
                    };

                    var get = function (append) {

                        var imps = [];
                        imps[0] = (append) ? read(file.input).append : read(file.input).prepend;

                        //Get imports of imports up to four levels
                        for (var i = 1; i < 5; i++) {

                            imps[i] = [];

                            _.each(imps[i - 1], function (importedFile) {

                                imps[i] = _.uniq(_.union(imps[i], (append) ? read(importedFile).append : read(importedFile).prepend));
                            });
                        }

                        return _.uniq(_.flatten(imps));

                    };

                    var join = function (files, append) {

                        //Remove repeated imports
                        _.each(_.uniq(_.flatten(files)), function (imp) {

                            var js = fs.readFileSync(imp).toString();

                            if (file.config.uglify && !/min.js$/.exec(path.basename(imp))) {

                                try {

                                    js = ugly.minify(js, {fromString: true, mangle: file.config.mangle}).code;

                                } catch (e) {

                                    throw {message: 'Error on line ' + e.line + ' col ' + e.col + ' ' + e.message + ' of ' + imp};
                                }
                            }

                            if (append) {

                                javascript = javascript + js;

                            } else {

                                javascript = js + javascript;

                            }
                        });
                    };

                    //Join Files
                    var appends = get(true);
                    var prepends = get(false);
                    join(appends, true);
                    join(prepends, false);

                    _.each(importReg, function (reg) {

                        javascript = javascript.replace(new RegExp(reg.source + '\n', 'gi'), '');
                    });

                    try {
                        fs.outputFileSync(file.output, javascript);
                    } catch (e) {
                        throw e;
                    }
                };
Ejemplo n.º 10
0
var fs = require('fs'),
    UglifyJS = require('uglify-js'),
    _ = require('underscore');

var packageInfo = JSON.parse(fs.readFileSync('./package.json', {encoding: 'utf-8'})),
    name = packageInfo.name,
    version = packageInfo.version,
    file = './' + name + '.js',
    minimizedFile = './' + name + '-min.js',
    repo = 'https://github.com/jhudson8/' + name,
    content = fs.readFileSync(file, {encoding: 'utf8'}),
    versionMatcher = new RegExp(name + ' v[0-9\.]+');

content = content.replace(versionMatcher, name + ' v' + version);
fs.writeFileSync(file, content, {encoding: 'utf8'});

var minimized = UglifyJS.minify(file);
var minimizedHeader = '/*!\n * ' + repo + ' v' + version + ';  MIT license; Joe Hudson<joehud_AT_gmail.com>\n */\n';
fs.writeFileSync(minimizedFile, minimizedHeader + minimized.code, {encoding: 'utf8'});
Ejemplo n.º 11
0
Archivo: build.js Proyecto: ngot/ngMD
function compile() {
	return UglifyJS.minify(wrapper(), {fromString: true}).code;
}
Ejemplo n.º 12
0
'use strict';

var ujs = require('uglify-js');
var code = '40 + 2';
var ast = ujs.parse(code, {});
if (ast.body[0].body.operator === '+') {
  var code2 = 'var b = function () {};';
  var result = ujs.minify(code2, { fromString: true });
  if (result.code === 'var b=function(){};') {
    console.log('ok');
  }
}
Ejemplo n.º 13
0
app.get('/:user/:project/:version/:file', function(req, res) {
    if (req.params.user !== 'bootstrap-components') return res.send(404);

    var name = req.params.project;
    var project = projects[name];
    if (!project) return res.send(404);
    var file = req.params.file;
    var result;


    if (file === 'component.json') {
        var pkg = {
            name: name,
            repo: "bootstrap-components/"+name,
            description: "Bootstrap "+name+" component",
            version: "3.0.0",
            license: "Apache 2.0"
        };
        if (project.styles) pkg.styles = ['index.css'];
        if (project.scripts) {
            pkg.scripts = ['index.js'];
            pkg.main = project.scripts[0];
            pkg.dependencies = {"component/jquery": "*"};
        }
        if (project.fonts) pkg.fonts = project.fonts;
        return res.send(JSON.stringify(pkg));
    }


    if (file === 'index.css') {
        result = '';

        result += CACHE['variables.less'];
        result += CACHE['mixins.less'];

        project.styles.forEach(function (filename) {
            result += CACHE[filename];
        });

        result = result.replace(/@import[^\n]*/gi, '');
        result = result;

        return new less.Parser({
            optimization: 0,
            filename: 'index.css'
        }).parse(result, function (err, tree) {
            if (err) throw JSON.stringify(err);

            res.set('Content-Type', 'text/plain');
            return res.send(copyright + tree.toCSS({
                compress: true
            }).replace(/\.\.\/.+?\//g, ''));
        });
    }


    if (file === 'index.js') {
        var content = project.scripts.map(function(filename) {
            return CACHE[filename];
        }).join('\n').replace(/[\"\']use strict[\"\']/gi, '');

        res.set('Content-Type', 'text/plain');
        return res.send(copyright + uglifyJS.minify(content, {
            fromString: true
        }).code);
    }


    if (project.fonts && ~project.fonts.indexOf(file)) {
        result = CACHE[file];

        res.set('Content-Type', 'application/octet-stream');
        return res.send(result);
    }

    return res.send(404);
});
Ejemplo n.º 14
0
function minify(str) {
  return uglify.minify(str, {fromString: str});
}
Ejemplo n.º 15
0
var appClientFiles = [
  'app_client/app.js',
  'app_client/home/home.controller.js',
  'app_client/about/about.controller.js',
  'app_client/locationDetail/locationDetail.controller.js',
  'app_client/reviewModal/reviewModal.controller.js',
  'app_client/common/services/geolocation.service.js',
  'app_client/common/services/loc8rData.service.js',
  'app_client/common/filters/formatDistance.filter.js',
  'app_client/common/filters/addHtmlLineBreaks.filter.js',
  'app_client/common/directives/ratingStars/ratingStars.directive.js',
  'app_client/common/directives/footerGeneric/footerGeneric.directive.js',
  'app_client/common/directives/navigation/navigation.directive.js',
  'app_client/common/directives/pageHeader/pageHeader.directive.js'
];
var uglified = UglifyJS.minify(appClientFiles, {compress : false });

fs.writeFile('public/angular/loc8r.min.js', uglified.code, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log('Script generated and saved: loc8r.min.js');
  }
});

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
Ejemplo n.º 16
0
'use strict'

var fs = require('fs')
var peg = require('pegjs')
var uglify = require('uglify-js')

var index = fs.readFileSync(__dirname + '/index.js', 'utf8')
var parser = peg.buildParser(fs.readFileSync(__dirname + '/grammer.pegjs', 'utf8'), {trackLineAndColumn: true, output: 'source'})

var result = '// This file is automatically generated from the contents of `/src` using `/src/compile.js`\n\n' + index.replace("import './grammer.pegjs'", parser)

var minify = true
if (minify) {
  result = uglify.minify(result, {
    fromString: true,
    output: { ascii_only: true, indent_level: 2, beautify: true }
  }).code
}
Function('exports,module,require', result)(exports, module, require)

// If we're being called from the command line, output the file
//if (require.main && require.main.id === module.id) {
  fs.writeFileSync(__dirname + '/../index.js', result, 'utf8')
//}
Ejemplo n.º 17
0
  compress: function(classId, jsCode, envMap, options) {
    var opts = {};
    var compressedCode = jsCode;

    if (!options) {
      options = {};
    }

    // merge options and default values
    opts = {
      privates: options.privates === false ? false : true,
      cachePath: options.cachePath === undefined ? null : options.cachePath,
    };
    // Special handling for regular expression literal since we need to
    // convert it back to a regex object, otherwise it will be decoded
    // as a string and the regular expression would be lost.
    var adjustRegexLiteral = function(key, value) {
      // deserialize regex strings (e.g. "/my[rR]egex/i") but
      // ignore strings containing paths (e.g. /source/class/foo/).
      if (key === 'value'
          && typeof(value) === "string"
          && value.match(/^\/.*\/[gmsiy]*$/)
          && value.match(/^\/(\w+\/)+$/) === null) {
        if (value.slice(-1) === "/") {
          value = new RegExp(value.substring(1, value.length-1));
        } else {
          var posOfSlash = value.lastIndexOf("/");
          value = new RegExp(value.substr(1, posOfSlash-1), value.substr(posOfSlash+1));
        }
      }
      return value;
    };
    var debugClass = function(classId) {
      if (classId === "qx.REPLACE.THIS") {
        var escg = require("escodegen");
        console.log("comp", escg.generate(tree));
      }
    };

    // compress with UglifyJS2

    // if there's an esprima AST use it
    var cacheOrNull = (opts.cachePath) ? new qx.tool.Cache(opts.cachePath) : null;

    if (cacheOrNull) {
      var curCacheId = cacheOrNull.createCacheId('tree', envMap, classId);
      if (cacheOrNull.has(curCacheId)) {
        var tree = JSON.parse(cacheOrNull.read(curCacheId), adjustRegexLiteral);
        if (tree !== null && typeof(tree) !== 'undefined') {
          // debugClass(classId);
          var ast = U2.AST_Node.from_mozilla_ast(tree);
          ast.figure_out_scope();
          var compressor = U2.Compressor({warnings: false});
          ast = ast.transform(compressor);
          compressedCode = ast.print_to_string();
        }
      }
    }

    // compress in any case
    var result = U2.minify(compressedCode, {fromString: true});
    compressedCode = result.code;

    // qx specific optimizations
    if (opts.privates) {
      compressedCode = replacePrivates(classId, compressedCode);
    }

    return compressedCode;
  }
Ejemplo n.º 18
0
 function(cb) {
   var uglified = uglify.minify(original, {
     outSourceMap: sourceMapUrl
   });
   cb(null, uglified);
 },
Ejemplo n.º 19
0
 .then(() => util.write(`${dest}.min.js`, `${util.banner}\n${uglify.minify(`${dest}.js`).code}`))
Ejemplo n.º 20
0
  writeStream.on('close', () => {
    fs.createWriteStream(path.join(DIST_DIR, fileName.replace('.js', '.min.js')))
      .end(uglifyJS.minify([path.join(DIST_DIR, fileName)]).code);

    console.log(chalk.yellow('  ⇢  %s/%s'), DIST_DIR, fileName);
  });
Ejemplo n.º 21
0

var input = 'dev.html',
    output = 'index.html',
    zipped = 'min.zip',
    files = [];


var index = fs.readFileSync(input, 'utf8');
var $ = cheerio.load(index);
var script;
$('script').each(function() {
    script = $(this).attr('src'); 
    files.push(script);
});
var src = uglify.minify(files).code;
console.log('\n');
console.log('- Concated and uglified ' + files.length + ' js files');

// remove all script tags
index = index.replace(/<script[^>]*>.*?<\/script>/gi,'');
// append concatted and uglified as inline script
index = index.replace('</body>', '<script>'+src+'</script></body>');
// index = index.replace(/\s/g, "");

var zip = new require('node-zip')();
zip.file(output, index);
var data = zip.generate({base64:false,compression:'DEFLATE'});
fs.writeFileSync(zipped, data, 'binary');
console.log('- Zipped file: ' + zipped + ' created');
Ejemplo n.º 22
0
function doUglify(pkgName, code, prepend, fileOut) {
  var miniCode = prepend + UglifyJS.minify(code);
  return writeFile(addPath(pkgName, fileOut), miniCode);
}
Ejemplo n.º 23
0
//copy dist to test
cp('-rf',f.dist+'*', f.test+'js/');

if(argv.config=='release'){
	//generate docs
	rm('-rf', f.docs);
	mkdir(f.docs);
	mv(f.dist+'onQuery.xml',f.docs);
	exec('haxelib run dox -i '+f.docs+' -o '+f.docs+' -r /onQuery/docs/ --title onQuery',{async:true,silent:true}, function(code, output) {
		console.log('Generating docs:',code==0?'success':'failed');
	});
	
	//Minifying
	var UglifyJS = require('uglify-js');
	var result = UglifyJS.minify(f.dist+'onquery.js');
    /*! onQuery v1.11.0 | (c) 2014 Ayoub Kaanich | onquery.org/license */
    fs.writeFile(f.dist+'onquery.min.js',result.code,function(err){
		if(err)throw err;
		console.log('Minifying: done.');
	});
	
	render('package.json');
	render('README.md');
    
}

function render(name){
	fs.readFile(f.build_template+name,'utf-8', function (err, template) {
		if (err) throw err;
		var output = Mustache.render(template,config);
Ejemplo n.º 24
0
function minify(src) {
  return UglifyJS.minify(src, {fromString: true}).code;
}
Ejemplo n.º 25
0
				getBlocks(content).forEach(function(blk) {
					var dest		= blk.dest.split(" ");
					var blockTarg	= dest[1];
					var min;
					
					//	We need to determine if this page contains a test
					//	harness, so we check for test/framework.js in the 
					//	block includes, if any. We store these testable urls.
					//	
					//	@see	tasks/mocha.js for where these are checked.
					//
					grunt.__TESTED_PAGES__ = grunt.__TESTED_PAGES__ || {};
					blk.src.forEach(function(fname) {
						if(fname.indexOf(grunt.config.data.testFrameworkFile) > -1) {
							grunt.__TESTED_PAGES__[filepath] = 1;
						}
					});
					
					//	Given a directive like <!-- build:css:deploy css/style.min.css -->
					//	in source/index.html file, we want to write the minified file
					//	(css/style.min.css) to   build/deploy/css/style.min.css
					//	where stage and deploy are ^   ^ Note the :deploy part of directive
					//												^ could also be :stage
					//
					//	Note that there *must* be a stage || deploy target, and a dest file name.
					//
					dest = dest.length === 2	
						?	dest = htmlFile.dest + "/" + buildDir + subDir + blockTarg
						:	null;

					if(dest && blk.src.length) {
					
						//	For each of the file paths in this block modify path
						//	so that it points to source/.../blockpath, simultaneously
						//	copying over these source files into stage & deploy
						//
						blk.src = blk.src.map(function(b) {
						
							var src = sourceDir + b;
							var dst = htmlFile.dest + "/" + buildDir + subDir + b;
							grunt.file.copy(src, dst);
							grunt.log.writeln(dst + '" created.');

							return src;
						});
						
						//	For css we need to concat individuals, as clean-css doesn't 
						//	seem to allow multiple files to be minified programatically.
						//	For js, we min the group #blk.src
						//
						min =	blk.type === "css"	
								?	blk.src.reduce(function(prev, cur) {
										return prev + cleanCSS.process(grunt.file.read(cur));
									}, "")
								:	blk.type === "js"
									?	uglify.minify(blk.src).code
									:	null;

						if(min) {
							grunt.file.write(dest, min);
							grunt.log.writeln(dest + '" created.');
						}
					}
				});
Ejemplo n.º 26
0
var uglify = require('uglify-js')
  , jsClient = uglify.minify(__dirname + '/client.js').code
  , winston
  ;

function getClient(req, res) {
  res.header('Content-Type', 'application/javascript');
  res.end(jsClient);
}

function logMessage(req, res) {
  var meta = ( req.params.meta
             ? JSON.parse(req.params.meta)
             : '' );
  winston.log(req.params.level, req.params.message, meta);
  res.json({got: 'it'});
}

function helpExpress(app, _winston) {
  winston = _winston;
  jsClient = jsClient.replace('{LEVELS:LEVELS}', JSON.stringify(winston.levels));
  app.get('/winston/client.js', getClient);
  app.get('/winston/log/:level/:message/:meta?', logMessage);
}

module.exports = helpExpress;
Ejemplo n.º 27
0
.then(function () {
  return write(
    'dist/clantu.min.js',
    banner + '\n' + uglify.minify('dist/clantu.js').code
  )
})
Ejemplo n.º 28
0
var sendevent = require('sendevent');
var watch = require('watch');
var uglify = require('uglify-js');
var fs = require('fs');
var ENV = process.env.NODE_ENV || 'development';
var path = require('path');

var clientScript = fs.readFileSync( path.resolve('./') + '/asset/client-script.js', 'utf8');
var script = uglify.minify(clientScript, { fromString: true }).code;

function reloadify(app, dir) {

  //不是开发环境不生效
  if (ENV !== 'development') {
    app.locals.watchScript = '';
    return;
  }

  //创建一个/eventstream事件, 用于发送消息
  var events = sendevent('/eventstream');
  console.info(ENV+" sis env");

  app.use(events);

  //检测文件是否发生变化 有就发送消息
  watch.watchTree(dir, function (f, curr, prev) {
    events.broadcast({ msg: 'reload' });
  });

  // 声明一个变量,以供前端嵌入 js 代码
  app.locals.watchScript = '<script>' + script + '</script>';
Ejemplo n.º 29
0
	grunt.registerMultiTask( 'grunticon', 'A mystical CSS icon solution.', function() {
		var done = this.async();

		// get the config
		var config = this.options({
			datasvgcss: "icons.data.svg.css",
			datapngcss: "icons.data.png.css",
			urlpngcss: "icons.fallback.css",
			files: {
				loader: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.js'),
				banner: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.banner.js')
			},
			previewhtml: "preview.html",
			loadersnippet: "grunticon.loader.js",
			cssbasepath: path.sep,
			customselectors: {},
			cssprefix: ".icon-",
			defaultWidth: "400px",
			defaultHeight: "300px",
			colors: {},
			pngfolder: "png",
			template: "",
			autoRunJS: "",
			previewTemplate: path.join( __dirname, "..", "example", "preview.hbs" )
		});

		// just a quick starting message
		grunt.log.writeln( "Look, it's a grunticon!" );

		var files = this.files.filter( function( file ){
			return file.src[0].match( /png|svg/ );
		});
		if( files.length === 0 ){
			grunt.log.writeln( "Grunticon has no files to read!" );
			done();
		}

		files = files.map( function( file ){
			return file.src[0];
		});

		config.src = this.files[0].orig.cwd;
		config.dest = this.files[0].orig.dest;

		// folder name (within the output folder) for generated png files
		var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );

		// create the output directory
		grunt.file.mkdir( config.dest );

		// minify the source of the grunticon loader and write that to the output
		grunt.log.writeln( "grunticon now minifying the stylesheet loader source." );
		var banner = grunt.file.read( config.files.banner );
		var min = banner + "\n" + uglify.minify( config.files.loader ).code;
		// if autoRunJS, append function to output
		if ( config.autoRunJS !== "" ) {
			var autoload = "grunticon([" + [
				"'" + config.autoRunJS + "/" + config.datasvgcss + "'",
				"'" + config.autoRunJS + "/" + config.datapngcss + "'",
				"'" + config.autoRunJS + "/" + config.urlpngcss + "'"
				].join(",") + "]);";
			min += autoload;
		}
		grunt.file.write( path.join( config.dest, config.loadersnippet ), min );
		grunt.log.writeln( "grunticon loader file created." );

		var svgToPngOpts = {
			pngfolder: pngfolder,
			defaultWidth: config.defaultWidth,
			defaultHeight: config.defaultHeight
		};

		var o = {
			pngfolder: pngfolder,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: false,
			prefix: config.cssprefix
		};

		var o2 = {
			pngfolder: pngfolder,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: true,
			prefix: config.cssprefix
		};

		grunt.log.writeln("Coloring SVG files");
		var colorFiles;
		var tmp = path.resolve( "tmp" );
		grunt.file.mkdir( tmp );
		try{
			var dc = new DirectoryColorfy( config.src, tmp, {
				colors: config.colors
			});
			colorFiles = dc.convert();
		} catch( e ){
			grunt.fatal(e);
			done( false );
		}

		//copy non color config files into temp directory
		var transferFiles = this.files.filter( function( f ){
			return !f.src[0].match( /\.colors/ );
		});

		transferFiles.forEach( function( f ){
			var filenameArr = f.src[0].split( "/" ),
				filename = filenameArr[filenameArr.length - 1];
			grunt.file.copy( f.src[0], path.join( tmp, filename ) );
		});

		grunt.log.writeln("Converting SVG to PNG");
		svgToPng.convert( tmp, config.dest, svgToPngOpts )
		.then( function( result , err ){
			if( err ){
				grunt.fatal( err );
			}

			var svgde = new DirectoryEncoder(tmp, path.join( config.dest, config.datasvgcss ), o ),
				pngde = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.datapngcss ), o ),
				pngdefall = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.urlpngcss ), o2 );

			grunt.log.writeln("Writing CSS");
			try {
				svgde.encode();
				pngde.encode();
				pngdefall.encode();
			} catch( e ){
				grunt.fatal( e );
				done( false );
			}

			grunt.log.writeln( "Grunticon now creating Preview File" );
			try {
				helper.createPreview(tmp, config.dest, config.defaultWidth, config.defaultHeight, min, config.previewhtml, config.cssprefix, config.previewTemplate);
			} catch(er) {
				grunt.fatal(er);
			}


			grunt.log.writeln( "Delete Temp Files" );
			grunt.file.delete( tmp );
			done();
		});

	});
Ejemplo n.º 30
0
var uglifyHandler = function(args, inputText, callback) {
  var result = uglify.minify(inputText, {fromString: true})

  callback(null, result.code)
}