Example #1
0
		cssMinifier:function(fileIn,fileOut){
			var fileIn=Array.isArray(fileIn)? fileIn : [fileIn],
     			 filedata,finalCode='';
     		for(var i=0; i<fileIn.length; i++) {
        		filedata = fs.readFileSync(fileIn[i], 'utf8');
        		finalCode = Config.short ? (finalCode + filedata ) : (finalCode + cleanCss.process(filedata)); 
     		}
     		console.log('fileOut='+fileOut+',finalCode(30)='+finalCode.substring(0,30));
     		console.log('before successful');
    		fs.writeFileSync(fileOut, finalCode, 'utf8');	
			console.log('writefile--before successful');
		}
Example #2
0
			}).replace(/<link href=([\'\"])(?!https?\:\/\/)(.*?)(\1) rel="stylesheet"\/>/g, function(r,quot,m){

				var path = (m.match(/^\//) ? opts.root_dir : '' ) + m ;
				console.log("Embed css: "+ path);

				// remove Byte Order mark with replace
				var str = fs.readFileSync(path).toString().replace(/^\uFEFF/, '');
				if(opts.minify){
					str = cleanCSS.process(str);
				}
				return '<style>'+str+'</style>';
			});
Example #3
0
		}, function(error) {
			if (error) self.emit('error', error);
			self.contents = '';
			if (isProduction) {
				_.each(self.assets, function(asset) {
					self.contents += asset.contents + '\n';
				});
				self.contents = cleancss.process(self.contents);
			}
			self.isDev = false;
			self.emit('created');
		});
Example #4
0
File: util.js Project: QETHAN/projs
  /** 
   * 压缩文件
   * @param {String} [codeStr] [源码]
   * @param {String} [fileType] [文件类型,默认为js]
   */
  function getSourceByCompress(codeStr,Opts){
    var ast,
      fileType = Opts && Opts.file && Opts.file.type || 'js',
      compressor,
      isError,
      cssBR = '\n',
      commentText = '';

    if(fileType == 'js'){
      try{
      ast = uglify.parse(codeStr);
      }catch(e){
        isError = true; 
      }

      if(!isError){
        // 保证输出风格美观,此处判断是否压缩
        if(Opts.isMini){
          ast.figure_out_scope();
          ast.mangle_names();
          compressor = uglify.Compressor({
            sequences: false,
            warnings: false
          });
          ast = ast.transform(compressor);
          codeStr = ast.print_to_string()+'';
        }else{
          codeStr = ast.print_to_string({
            beautify: true,
            indent_level: 2
          });
        }
      }
    }else{
      commentText = formatCommentText(Opts.commentText,fileType)
      // 如果压缩
      if(Opts.isMini){
        cssBR = '';
        codeStr = cleanCSS.process(codeStr);
      }
      
      codeStr = codeStr.replace(cssRubReg,'');
      codeStr = '@charset "'+(Opts.config.css_charset || 'utf-8')+'"\;'+cssBR+codeStr;

      // 如果要设置版本
      if(codeStr && Opts.addImageVersion){
       return commentText + setCSSImageVersion(codeStr,Opts);
      }
    }

    return commentText + codeStr;
  }
Example #5
0
    return helper.mapList(list, function(type, code, filepath) {

        switch(type) {
            case 'js':
                return uglifyJS.minify(code, {fromString: true}).code;
            case 'css':
                return cleanCSS.process(code);
            default:
                return code;

        }

    }, this);
Example #6
0
function css2js(code, id, options, fileObj) {
  // ex. arale/widget/1.0.0/ => arale-widget-1_0_0
  var styleId = unixy((options || {}).idleading || '')
    .replace(/\/$/, '')
    .replace(/\//g, '-')
    .replace(/\./g, '_');
  var prefix = ['.', styleId, ' '].join('');

  var addStyleBox = false;
  if (options.styleBox === true) {
    addStyleBox = true;
  } else if (options.styleBox && options.styleBox.length) {
    options.styleBox.forEach(function(file) {
      if (file === fileObj.name) {
        addStyleBox = true;
      }
    });
  }

  // if outside css modules, fileObj would be undefined
  // then dont add styleBox
  if (addStyleBox && styleId && fileObj) {
    var data = cssParse(code);
    data.stylesheet.rules = parseRules(data.stylesheet.rules, prefix);
    code = cssStringify(data);
  }

  // remove comment and format
  var cleancss = require('clean-css');
  code = cleancss.process(code, {
    keepSpecialComments: 0,
    removeEmpty: true
  });

  // transform css to js
  // spmjs/spm#581
  var tpl = [
    'define("%s", [], function() {',
    "seajs.importStyle('%s')",
    '});'
  ].join('\n');

  // spmjs/spm#651
  code = code.split(/\r\n|\r|\n/).map(function(line) {
    return line.replace(/\\/g, '\\\\');
  }).join('\n');

  code = format(tpl, id, code.replace(/\'/g, '\\\''));
  return code;
}
        uncss(this.options.uncss.files, this.options.uncss.options, function(error, output) {
            if(self.options.cleancss != null) {
                try {
                    output = cleancss.process(output, self.options.cleancss);
                } catch(_error) {
                    error = "Clean CSS: CSS minify failed on " + path + ": " + _error;
                }
            }

            return process.nextTick(function() {
                return callback(error, output || data);
            });

        });
Example #8
0
 input.onkeyup = function() {
   var source = input.innerHTML;
   var minimized = cleanCSS.process(source);
   output.innerHTML = minimized;
   minimized = null;
   Prism.highlightAll(true, null);
   if(output.innerHTML.length > 4) {
     copyBtn.removeAttribute('disabled');
     copyBtn.classList.remove('off');
   } else {
     copyBtn.setAttribute('disabled');
     copyBtn.classList.add('off');
   }
 };
Example #9
0
function minifyComponent(name) {
    var p = promise();

    var distDir = path.join('dist', name);
    console.log(distDir);

    // make dist directory if necessary
    if (!fs.existsSync(distDir)) {
        fs.mkdirSync(distDir);
    }

    var jsPath = path.join(distDir, name + '.min.js');
    console.log(jsPath);
    var srcJsPath;
    // special case to account for the x-tag core submodule
    if(name === "core"){
        srcJsPath = path.join('component', "core", 'src', 
                              "x-tag-core", "dist", "x-tag-core.js");
    }
    else{
        srcJsPath = path.join('component', name, 'src', name + '.js');
    }

    try {
        var js = uglifyjs.minify(srcJsPath);
        fs.writeFileSync(jsPath, js.code);
    } catch (e) {
        p.reject(e);
        return p;
    }

    var cssPath = path.join(distDir, name + '.min.css');
    console.log(cssPath);
    try {
        var css = fs.readFileSync(path.join('component', name, 'src', name + '.css')).toString();
        css = cleancss.process(css);
        fs.writeFileSync(cssPath, css);
    } catch (e) {
        p.reject(e);
        return p;
    }

    if (typeof js !== 'undefined' && typeof css !== 'undefined') {
        p.fulfill({css: css, js: js.code});
    } else {
        throw "missing resulting source";
    }
    return p;
}
Example #10
0
function cssMinifier(flieIn, fileOut) {

    var flieIn=Array.isArray(flieIn)? flieIn : [flieIn];

    var origCode,finalCode='';

    for(var i=0; i<flieIn.length; i++) {

        origCode = fs.readFileSync('public/'+flieIn[i], 'utf8');

        finalCode += cleanCSS.process(origCode);

    }

    fs.writeFileSync('public/stylesheets/prod/'+fileOut, finalCode, 'utf8');

}
Example #11
0
var transform = exports.transform = function (input, basedir, datauri, fixIE, toAbsolutePath, workspaceRoot) {
		if(datauri){
			input = DataURICommand.transform(input, basedir, fixIE);
		}
		if(toAbsolutePath && workspaceRoot){
			input = input.replace(/background.*url\(\s*\"?\'?(\S*)\.(png|jpg|jpeg|gif|svg\+xml)\"?\'?\s*\).+/gi, function (match, file, type) {
				if(!file || file[0] === '/'){
					return match;
				}
				var fileName = basedir + "/" + file + '.' + type;
				var absolutePath = path.normalize("/" + path.relative(workspaceRoot, path.dirname(fileName)) + "/" + path.basename(file) + "." + type);
				absolutePath = absolutePath.replace(/\\/g, "/");
				return match.replace(/url\(\s*\"?\'?(\S*)\.(png|jpg|jpeg|gif|svg\+xml)\"?\'?\s*\)/i, "url("+absolutePath+")");
			});
		}
        return cleanCSS.process(input);
};
Example #12
0
/**
 * @param code {Buffer|String}
 * @param option {Object}
 *         - removeEmpty cleancss's setting
 *         - charset default 'utf-8'
 *
 * @return {Buffer} option.charset encoded buffer
 */
function compress(code, option) {
  var defaultEncoding = 'utf-8';
  option || (option = {});
  option.charset || (option.charset = defaultEncoding);

  var buf = helper.iconv(option.charset, defaultEncoding, code);
  code = buf.toString(defaultEncoding);


  var css = sorter.sort(code);

  if (!option.debug) {
    css = minfier.process(css, option);
  }

  var newBuf = helper.iconv(defaultEncoding, option.charset, css);

  return newBuf;
}
Example #13
0
                html = html.replace(reStackedTag, function (all, text) {
                    if (stackedTag !== 'script' && stackedTag !== 'style') {
                        text = text
                            .replace(/<!--([\s\S]*?)-->/g, "$1")
                            .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
                    }

                    if (stackedTag == 'style') {
                        text = minifyCSS(text);
                    }

                    if (stackedTag == 'script') {
                        text = uglifyJS.minify(text, {fromString: true}).code;
                    }

                    if (handler.chars)
                        handler.chars(text);

                    return "";
                });
Example #14
0
    css: function(opts, mappath) {
      console.log('Loading CSS files...');

      var source = fs.readFileSync(mappath(opts.input), 'utf8');

      source = source.replace(CSS_INCLUDE, function(line) {
        var path = line.match(/"(.+?)"/)[1];
        console.log(opts.path + '/' + path);
        //css "includes" are specified relative to current path
        return fs.readFileSync(mappath(opts.path, path), 'utf8');
      });

      console.log('\nAssembling' + (opts.noMinify ? '' : ' and Minifying') + ' CSS...');
      if (!opts.noMinify) {
        //use clean-css for minification
        source = cleanCSS.process(source, {keepSpecialComments: 0});
      }
      fs.writeFileSync(mappath(opts.output), source, 'utf8');
      console.log('Done.\n');
    },
Example #15
0
    target.minify = function () {
        cd(ROOT_DIR);
        echo();
        echo("### Minifying css files...");

        // pack.css

        var inCss = cat(["site/css/normalize.css",
                         "site/css/all.css",
                         "site/css/demo.css"
        ]);

        var packCss = cleanCSS.process(inCss, {
            removeEmpty: true,
            keepSpecialComments: 0
        });

        fs.writeFileSync("site/css/pack.css", packCss, "utf8");

        echo();
        echo("### Finished site/css/pack.css.");

        echo();
        echo("### Minifying js files...");

        var inJs = cat(["site/js/cppcheck.js",
                        "site/js/github.js",
                        "site/js/picnet.table.filter.min.js"]);

        var minifiedJs = UglifyJS.minify(inJs, {
            compress: true,
            fromString: true, // this is needed to pass JS source code instead of filenames
            mangle: true,
            warnings: false
        });

        fs.writeFileSync("site/js/pack.js", minifiedJs.code, "utf8");

        echo();
        echo("### Finished site/js/pack.js.");
    };
Example #16
0
	var processor = function(rules, callback, options) {
		options = options || defaultOptions;
		var css = '';
		for(var stylesheet in rules) {
			var r = filterRules(rules[stylesheet]);
			r = options.combineSelectors ? combineSelectors(r) : r;
			if(stylesheet === "mainstream") {
				css += toCSS(r, options);
			} else {
				css += stylesheet + " {" + newline + toCSS(r, options) + "}" + newline;
			}		
		}
		// Minification
		if(options.minify) {
			css = cleanCSS.process(css);
			if(callback) callback(null, css);
		} else {
			if(callback) callback(null, css);
		}
		return css;
	}
Example #17
0
	function css(filepath, fileContent, relativeTo, options) {
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//g, relativeTo);
	    }

		fileContent = fileContent.replace(/url\(["']*([^)'"]+)["']*\)/g, function(matchedWord, imgUrl){
			var newUrl = imgUrl;
			var flag = imgUrl.indexOf(options.tag)!=-1;	// urls like "img/bg.png?__inline" will be transformed to base64
			if(isBase64Path(imgUrl)) {
				grunt.log.debug('css(): not escaping: isBase64Path:' + imgUrl + '\n');
				return matchedWord;
			}
			if (isRemotePath(imgUrl)){
				grunt.log.debug('css(): not escaping: isRemotePath:' + imgUrl + '\n');
				return matchedWord;
			}
			grunt.log.debug( 'css(): imgUrl: '+imgUrl +'\n');
			grunt.log.debug( 'css(): filepath: '+filepath +'\n');
			var absoluteImgurl = path.resolve( path.dirname(filepath),imgUrl );
			grunt.log.debug( 'css(): absoluteImgurl: '+absoluteImgurl +'\n');
			newUrl = path.relative( path.dirname(filepath), absoluteImgurl );
			grunt.log.debug( 'css(): newUrl: '+newUrl +'\n');

			absoluteImgurl = absoluteImgurl.replace(/\?.*$/, '');
			if(flag && grunt.file.exists(absoluteImgurl)){
				newUrl = datauri(absoluteImgurl);
				grunt.log.debug( 'css(): flag&&grunt.file.exists(absoluteImgurl) newUrl: '+newUrl + '\n');
			}else{
				newUrl = newUrl.replace(/\\/g, '/');
				grunt.log.debug( 'css(): ! flag&&grunt.file.exists(absoluteImgurl) newUrl: '+newUrl + '\n');
			}

			grunt.log.debug( 'css(): newUrl: '+newUrl + '\n');
			return matchedWord.replace(imgUrl, newUrl);
		});
		fileContent = options.cssmin ? CleanCSS.process(fileContent) : fileContent;

		return fileContent;
	}
Example #18
0
exports.optimizecss = function(inputFile, outputFile, options, charset){
    var cleanCSS = require('clean-css');
    var contents = file.read(inputFile, charset);
    // skip empty files
    if (contents.length) {

        var urlFromBase = options.urlFromBase;
        var urlToBase = options.urlToBase;

        if(urlFromBase && !exports.file.isDirname(urlFromBase)){
            urlFromBase = path.dirname(urlFromBase);
        }

        if(urlToBase && !exports.file.isDirname(urlToBase)){
            urlToBase =  path.dirname(urlToBase);
        }


        if(!options.relativeTo){
            options.relativeTo = urlFromBase;
        }

        var minimized = cleanCSS.process(contents, options);

        // url relocate
        contents = exports.urlRelocate(minimized, urlFromBase, urlToBase, options.urlPrepend, options.revDest);

        // output to file
        if(outputFile){
            file.write(outputFile, contents, charset);
            exports.log(inputFile, '>', outputFile);
        }

    } else {
        exports.log("Skipping empty file" ,  inputFile);
    }
    return contents;
};
Example #19
0
function css2js(code, options, fileObj) {
  var addStyleBox = false;
  if (options.styleBox === true) {
    addStyleBox = true;
  } else if (options.styleBox && options.styleBox.length) {
    options.styleBox.forEach(function(file) {
      if (file === fileObj.name) {
        addStyleBox = true;
      }
    });
  }

  // if outside css modules, fileObj would be undefined
  // then dont add styleBox
  var opt = {};
  if (addStyleBox && fileObj) {
    // ex. arale/widget/1.0.0/ => arale-widget-1_0_0
    var styleId = unixy((options || {}).idleading || '')
      .replace(/\/$/, '')
      .replace(/\//g, '-')
      .replace(/\./g, '_');
    opt.prefix = ['.', styleId, ' '].join('');
  }

  code = css2str(code, opt);

  // remove comment and format
  code = cleancss.process(code, {
    keepSpecialComments: 0,
    removeEmpty: true
  });

  // transform css to js
  // spmjs/spm#581
  var template = 'function() {seajs.importStyle(\'%s\')}';
  return format(template, code);
}
Example #20
0
var task = exports.task = function(inputFile, outputFile, options, charset){

    charset = charset || "utf-8";
    var input = fs.readFileSync(inputFile, charset);

    // skip empty files
    if (input.length) {

        if(outputFile){
            exports.log("Minifying " + inputFile + " > " + outputFile);
        }

        var minimized = cleanCSS.process(input);

        // output to file
        if(outputFile){

            file.write(outputFile, minimized, charset);

            // TODO DRY
            var diff = input.length - minimized.length,
                savings = input.length ? ((100 * diff) / minimized.length).toFixed(2) : 0;
            var info = 'Original size: ' + format.commify(input.length)  +
                '. Minified size: ' + format.commify(minimized.length) +
                '. Savings: ' + format.commify(diff) + ' (' + savings + '%)';

            exports.log(info);
        }

        return minimized;

    } else {
        exports.log("Skipping empty file" ,  inputFile);
    }


};
Example #21
0
MinifyCss.prototype.processFile = function(filepath) {
	var source,
		fileDest;
	if (path.extname(filepath) !== '.css') {
		return;
	}
	if (this.ignore != null && this.ignore.test(filepath)) {
		return;
	}
	fileDest = path.join(
		path.dirname(filepath), 
		path.basename(filepath, path.extname(filepath)) + this.ext
	);

	this.logger.info({
		ja: 'CSSを圧縮します。',
		en: 'Minifying CSS',
		path: filepath
	});

	source = fs.readFileSync(filepath, 'utf8');
	if (source.indexOf('@import') >= 0) {
		this.filesWithImports.push(fileDest);
	}
	source = cleanCSS.process(source);

	fs.writeFileSync(fileDest, source, 'utf8');
	if (fileDest !== filepath) {
		this.fileChanges.moveFile(filepath, fileDest);
		if (this.config.keep_original) {
			this.fileChanges.keepFile(filepath);
		}
	} else {
		this.fileChanges.keepFile(filepath);
	}
}
Example #22
0
function css2js(code, id, options) {
  // ex. arale/widget/1.0.0/ => arale-widget-1_0_0
  var styleId = unixy((options || {}).idleading || '')
    .replace(/\/$/, '')
    .replace(/\//g, '-')
    .replace(/\./g, '_');
  var prefix = ['.', styleId, ' '].join('');
  if (options.styleBox === true && styleId) {
    var data = cssParse(code);
    data.stylesheet.rules = parseRules(data.stylesheet.rules, prefix);
    code = cssStringify(data);
  }

  // remove comment and format
  var cleancss = require('clean-css');
  code = cleancss.process(code, {
    keepSpecialComments: 0,
    removeEmpty: true
  });

  // transform css to js
  // spmjs/spm#581
  var tpl = [
    'define("%s", [], function() {',
    "seajs.importStyle('%s')",
    '});'
  ].join('\n');

  // spmjs/spm#651
  code = code.split(/\r\n|\r|\n/).map(function(line) {
    return line.replace(/\\/g, '\\\\');
  }).join('\n');

  code = format(tpl, id, code.replace(/\'/g, '\\\''));
  return code;
}
Example #23
0
var mincss = function(css) { return cleancss.process(css); };
Example #24
0
MobileWebBuilder.prototype.assembleTitaniumCSS = function assembleTitaniumCSS(next) {
	var tiCSS = [
		ejs.render(fs.readFileSync(path.join(this.templatesDir, 'header.ejs')).toString()), '\n'
	];

	if (this.tiapp.mobileweb.splash.enabled) {
		var splashDir = path.join(this.projectResDir, 'mobileweb', 'splash'),
			splashHtmlFile = path.join(splashDir, 'splash.html'),
			splashCssFile = path.join(splashDir, 'splash.css');

		if (fs.existsSync(splashDir)) {
			this.logger.info(__('Processing splash screen'));
			fs.existsSync(splashHtmlFile) && (this.splashHtml = fs.readFileSync(splashHtmlFile));
			if (fs.existsSync(splashCssFile)) {
				var css = fs.readFileSync(splashCssFile).toString();
				if (this.tiapp.mobileweb.splash['inline-css-images']) {
					var parts = css.split('url('),
						i = 1, p, img, imgPath, imgType,
						len = parts.length;
					for (; i < len; i++) {
						p = parts[i].indexOf(')');
						if (p != -1) {
							img = parts[i].substring(0, p).replace(/["']/g, '').trim();
							if (!/^data\:/.test(img)) {
								imgPath = img.charAt(0) == '/' ? this.projectResDir + img : splashDir + '/' + img;
								imgType = this.imageMimeTypes[imgPath.match(/(\.[a-zA-Z]{3})$/)[1]];
								if (fs.existsSync(imgPath) && imgType) {
									parts[i] = 'data:' + imgType + ';base64,' + fs.readFileSync(imgPath).toString('base64') + parts[i].substring(p);
								}
							}
						}
					}
					css = parts.join('url(');
				}
				tiCSS.push(css);
			}
		}
	}

	this.logger.info(__('Assembling titanium.css'));

	var commonCss = this.mobilewebThemeDir + '/common.css';
	fs.existsSync(commonCss) && tiCSS.push(fs.readFileSync(commonCss).toString());

	// TODO: need to rewrite absolute paths for urls

	// TODO: code below does NOT inline imports, nor remove them... do NOT use imports until themes are fleshed out

	var themePath = path.join(this.projectResDir, 'themes', this.theme);
	fs.existsSync(themePath) || (themePath = path.join(this.projectResDir, this.theme));
	fs.existsSync(themePath) || (themePath = path.join(this.platformPath, 'themes', this.theme));
	if (!fs.existsSync(themePath)) {
		this.logger.error(__('Unable to locate theme "%s"', this.theme) + '\n');
		process.exit(1);
	}

	wrench.readdirSyncRecursive(themePath).forEach(function (file) {
		/\.css$/.test(file) && tiCSS.push(fs.readFileSync(path.join(themePath, file)).toString() + '\n');
	});

	// detect any fonts and add font face rules to the css file
	var fonts = {},
		fontFormats = {
			'ttf': 'truetype'
		},
		prefix = this.projectResDir + '/';

	(function walk(dir, isMobileWebDir, isRoot) {
		fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) {
			var file = path.join(dir, name);
			if (fs.statSync(file).isDirectory()) {
				if (!isRoot || name == 'mobileweb' || ti.availablePlatformsNames.indexOf(name) == -1) {
					walk(file, isMobileWebDir || name == 'mobileweb');
				}
				return;
			}

			var m = name.match(/^(.+)\.(otf|woff|ttf|svg)$/);
			if (m) {
				var p = file.replace(prefix, '').replace(/\\/g, '/');
				fonts[m[1]] || (fonts[m[1]] = []);
				fonts[m[1]].push({
					path: isMobileWebDir ? p.replace('mobileweb/', '') : p,
					format: fontFormats[m[2]] || m[2]
				});
			}
		});
	}(this.projectResDir, false, true));

	Object.keys(fonts).forEach(function (name) {
		var font = fonts[name],
			i = 0,
			l = font.length,
			src = [];

		this.logger.debug(__('Found font: %s', name.cyan));

		for (; i < l; i++) {
			this.prefetch.push(font[i].path);
			src.push('url("' + font[i].path + '") format("' + font[i].format + '")');
		}

		tiCSS.push('@font-face{font-family:"' + name + '";' + src.join(',') + ';}\n');
	}, this);

	// write the titanium.css
	fs.writeFileSync(path.join(this.buildDir, 'titanium.css'), this.deployType == 'production' ? cleanCSS.process(tiCSS.join('')) : tiCSS.join(''));

	next();
};
Example #25
0
var buildAppResource = function(appDir, theBinDir){
    var buildAppContent = '';
    var buildAppCssContent = '';

    var readPackage = function(path) {
      var url = path + '/package.js';
      var entireContent = fs.readFileSync(url, 'utf-8');
      var contentReg = /packages\s*\(\s*(.*)\s*\)/mg;
      var commentReg = /\/\/.*(\n|\r)|(\/\*(.*?)\*\/)/mg;
      var dirnameList = [];
         
      //去掉在package.js里的注释
      entireContent = entireContent.replace(commentReg, '');  
    
      //去掉换行符、换页符、回车符等
      entireContent = entireContent.replace(/\n|\r|\t|\v|\f/g, '');
      //取出参数, 存于dirnameList
      var result = contentReg.exec(entireContent);
      if (result === null) {
        return;
      }
      entireContent = result[1];
      entireContent = entireContent.replace(/'|"/mg, '');
      dirnameList = entireContent.split(',');

      dirnameList.forEach(function(dirname) {
        dirname = dirname.trim();
        if (!dirname) {
          return;
        }

        var reg = /.js$/g,
        cssReg = /.css$/g;

        var fileUrl = path + '/' + dirname;
        if (reg.test(dirname)) {
          buildAppContent += ';'+fs.readFileSync(fileUrl, 'utf-8');
        } else if (cssReg.test(dirname)) {
          buildAppCssContent += fs.readFileSync(fileUrl, 'utf-8');
        } else {
          readPackage(fileUrl);
        }
      });
    }

    readPackage(appDir);
    
    var UglifyJS = require('uglify-js');
  
    //压缩js代码
    var orig_code = buildAppContent;
    var ast = UglifyJS.parse(orig_code); // parse code and get the initial AST
    
    /*     
     * Compressor options
     * 
     * sequences     : true,  // join consecutive statemets with the “comma operator”
     * properties    : true,  // optimize property access: a["foo"] → a.foo
     * dead_code     : true,  // discard unreachable code
     * drop_debugger : true,  // discard “debugger” statements
     * unsafe        : false, // some unsafe optimizations (see below)
     * conditionals  : true,  // optimize if-s and conditional expressions
     * comparisons   : true,  // optimize comparisons
     * evaluate      : true,  // evaluate constant expressions
     * booleans      : true,  // optimize boolean expressions
     * loops         : true,  // optimize loops
     * unused        : true,  // drop unused variables/functions
     * hoist_funs    : true,  // hoist function declarations
     * hoist_vars    : false, // hoist variable declarations
     * if_return     : true,  // optimize if-s followed by return/continue
     * join_vars     : true,  // join var declarations
     * cascade       : true,  // try to cascade `right` into `left` in sequences
     * side_effects  : true,  // drop side-effect-free statements
     * warnings      : true,  // warn about potentially dangerous optimizations/code
     * global_defs   : {}     // global definitions
     * 
     * */
    
    var compressor = UglifyJS.Compressor({
        unused : false
    });
    ast.figure_out_scope();
    var compressed_ast = ast.transform(compressor);
    compressed_ast.figure_out_scope();
    compressed_ast.compute_char_frequency();
    compressed_ast.mangle_names(); // get a new AST with mangled names
    var packedAppContent = compressed_ast.print_to_string(); // compressed code here

    //clean css
    var cleanCSS = require('clean-css');
    var packedAppCssContent = cleanCSS.process(buildAppCssContent);
    
    
    if(typeof process.BAE !== 'undefined'){
        fs.writeFileSync(binDir + '/app.js', packedAppContent, 'utf-8');
        fs.writeFileSync(binDir + '/app.css', packedAppCssContent, 'utf-8');
        buildView(appDir, binDir);
        buildManifest(appDir, path.join(dstDir, 'bin'));
    }else{
        fs.writeFileSync(theBinDir + '/app.js', packedAppContent, 'utf-8');
        fs.writeFileSync(theBinDir + '/app.css', packedAppCssContent, 'utf-8');
        buildView(appDir, theBinDir);
        buildManifest(appDir, theBinDir);
    }
};
Example #26
0
scripts.forEach(function(name, i){
	unminifedJS.push( fs.readFileSync("./"+name, "utf8") );
	minifedJS.push( UglifyJS.minify("./"+name).code );
});


//
// Build Files
//
var build = {
	"../README.md" : htmlToMarkDown(fs.readFileSync("../index.html", "utf8")),
	"../dist/jquery.form.js" : unminifedJS.join('\n'),
	"../dist/jquery.form.min.js" : minifedJS.join('\n'),
	"../dist/jquery.form.css" : styles.join('\n'),
	"../dist/jquery.form.min.css" : cleanCSS.process(styles.join('\n')),
	"../dist/jquery.editor.js" : fs.readFileSync("./jquery.editor.js", "utf8"),
	"../dist/jquery.editor.min.js" : UglifyJS.minify("./jquery.editor.js").code,
	"../dist/jquery.editor.css" : fs.readFileSync("./jquery.editor.css", "utf8"),
	"../dist/jquery.editor.min.css" : cleanCSS.process(fs.readFileSync("./jquery.editor.css").toString()),
	"../dist/jquery.predict.js" : fs.readFileSync("./jquery.predict.js", "utf8"),
	"../dist/jquery.predict.min.js" : UglifyJS.minify("./jquery.predict.js").code,
	"../dist/jquery.predict.css" : fs.readFileSync("./jquery.predict.css", "utf8"),
	"../dist/jquery.predict.min.css" : cleanCSS.process(fs.readFileSync("./jquery.predict.css").toString())
};

for(var x in build){
	(function(name,code){
		fs.writeFile( name, code, function(err) {
			if(err) {
				console.log(err);
Example #27
0
Loader.transformStyle = function (input) {
  var cleaner = require('clean-css');
  return cleaner.process(input);
};
Example #28
0
var compressCss = function(src, target){
	var file = fs.readFileSync(src);
	var content = file.toString();
	var result = cleanCSS.process(content);
	nf.writeFileSync(target, result);
}
Example #29
0
File: build.js Project: AoJ/moment
 fs.readFile('./sitesrc/css/style.css', 'utf8', function(err, data){
     makeFile('./site/css/style.css', clean.process(data));
 });
Example #30
0
 return function(err, results) {
   if (err) throwError(err);
   if (results instanceof Array) results = results.join("\n");
   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'
   };
   switch(method) {
     case 'uglify':
       var ast = jsp.parse(results);
       ast = pro.ast_mangle(ast);
       ast = pro.ast_squeeze(ast);
       var final_code = pro.gen_code(ast);
       zlib.gzip(final_code, function(err, buffer) {
         if (err) throwError(err);
         S3.putGzipBuffer(buffer, encodeURIComponent(fileName), headers, function(err, response) {
           if (err) throwError(err);
           if (response.statusCode !== 200)
             throwError('unsuccessful upload of script "' + fileName + '" to S3');
           else
             console.log('successfully uploaded script "' + fileName + '" to S3');
         });
       });
       break;
     case 'minify':
       var minify = cleanCSS.process(results);
       zlib.gzip(minify, function(err, buffer) {
         if (err) throwError(err);
         S3.putGzipBuffer(buffer, encodeURIComponent(fileName), headers, function(err, response) {
           if (err) throwError(err);
           if (response.statusCode !== 200)
             throwError('unsuccessful upload of stylesheet "' + fileName + '" to S3');
           else
             console.log('successfully uploaded stylesheet "' + fileName + '" to S3');
         });
       });
       break;
     case 'optipng':
       var img = path.join(options.publicDir, assets);
       var optipng = spawn('optipng', [img]);
       optipng.stdout.on('data', function(data) {
         console.log('optipng: ' + data);
       });
       optipng.stderr.on('data', function(data) {
         throwError(data);
       });
       optipng.on('exit', function(code) {
         console.log('optipng exited with code ' + code);
         fs.readFile(img, function(err, data) {
           zlib.gzip(data, function(err, buffer) {
             S3.putGzipBuffer(buffer, encodeURIComponent(fileName), headers, function(err, response) {
               if (err) throwError(err);
               if (response.statusCode !== 200)
                 throwError('unsuccessful upload of image "' + fileName + '" to S3');
               else
                 console.log('successfully uploaded image "' + fileName + '" to S3');
                 // Hack to preserve original timestamp for view helper
                 fs.utimesSync(img, new Date(timestamp), new Date(timestamp));
             });
           });
         });
       });
       break;
     case 'jpegtran':
       var jpg = path.join(options.publicDir, assets);
       var jpegtran = spawn('jpegtran', [ '-copy', 'none', '-optimize', '-outfile', jpg, jpg ]);
       jpegtran.stdout.on('data', function(data) {
         console.log('jpegtran: ' + data);
       });
       jpegtran.stderr.on('data', function(data) {
         throwError(data);
       });
       jpegtran.on('exit', function(code) {
         console.log('jpegtran exited with code ' + code);
         fs.readFile(jpg, function(err, data) {
           zlib.gzip(data, function(err, buffer) {
             S3.putGzipBuffer(buffer, encodeURIComponent(fileName), headers, function(err, response) {
               if (err) throwError(err);
               if (response.statusCode !== 200)
                 throwError('unsuccessful upload of image "' + fileName + '" to S3');
               else
                 console.log('successfully uploaded image "' + fileName + '" to S3');
                 // Hack to preserve original timestamp for view helper
                 fs.utimesSync(jpg, new Date(timestamp), new Date(timestamp));
             });
           });
         });
       });
       break;
   }
 };