Ejemplo n.º 1
0
	fs.readFile(__dirname+'/less/compile.less', function (err, data) {
		if (err) {
			console.log(err);
			
			return res.send(500, {
				error: err,
				message: 'An error occured compiling the stylesheet',
				module: 'server',
				url: '/styles.css'
			});
		}
		
		var parser = new(less.Parser)({
		    paths: [__dirname, __dirname+'/less'], // Specify search paths for @import directives
		    filename: 'compile.less' // Specify a filename, for better error messages
		});
		
		parser.parse(data.toString(), function (err, tree) {
			if (err) {
				console.log(err);
				
				return res.send(500, {
					error: err,
					message: 'An error occured compiling the stylesheet',
					module: 'server',
					url: '/styles.css'
				});
			}
		
		    compiledLess = tree.toCSS({ compress: false }); // Minify CSS output
		
			res.setHeader('Content-type', 'text/css');
			res.send(compiledLess);
		});
	});
module.exports = function (file, pathStr, index, isLast, callback) {

	var paths = path.dirname(pathStr);

	var parser = new less.Parser({

		paths: paths

	});

	parser.parse(file, function (err, tree) {

		if (err){

			console.error(err);

		} else {

			callback(tree.toCSS());

		}
		
	});

};
Ejemplo n.º 3
0
 parse: ['read', function(cb, results) {
     var parser = new(less.Parser)({
         paths: [source('less')],
         filename: 'main.less'
     });
     parser.parse(results.read, cb);
 }],
Ejemplo n.º 4
0
  options.render = options.render || function(str, lessPath, cssPath, callback) {

    var paths = [ path.dirname(lessPath) ];
    options.paths.forEach(function(p){ paths.push(p); });

    var parser = new less.Parser({
      paths: paths,
      filename: lessPath,
      optimization: options.optimization,
      dumpLineNumbers: options.dumpLineNumbers,
      relativeUrls: options.relativeUrls
    });

    parser.parse(str, function(err, tree) {
        if(err) {
          return callback(err);
        }

        try {
          var css = tree.toCSS({
            compress: (options.compress == 'auto' ? regex.compress.test(cssPath) : options.compress),
            yuicompress: options.yuicompress,
            sourceMap: options.sourceMap
          });

          // Store the less import paths
          imports[lessPath] = determine_imports(tree, lessPath, options.paths);

          callback(err, css);
        } catch(parseError) {
          callback(parseError, null);
        }
    });
  };
Ejemplo n.º 5
0
Archivo: res.js Proyecto: guananddu/edp
    return function ( context ) {
        var docRoot  = context.conf.documentRoot;
        var pathname = context.request.pathname;
        var includePaths = context.conf.lessIncludePaths || [];
        var importPath = docRoot + path.dirname( pathname ).replace( /\/$/, '');
        var paths = [importPath];
        includePaths.forEach(function(pt) {
            paths.push(path.resolve(docRoot, pt));
        });

        var parser = new( less.Parser )( {
            paths: paths
        } );
        context.stop();

        parser.parse( 
            context.content.toString( encoding || 'utf8' ),
            function ( error, tree ) {
                if ( error ) {
                    context.status = 500;
                }
                else {
                    context.header[ 'Content-Type' ] = mimeType.css;
                    context.content = tree.toCSS();
                }

                context.start();
            }
        );
    };
Ejemplo n.º 6
0
/**
 * 编译less代码(异步)
 * 
 * @inner
 * @param {string} code less源代码
 * @param {Object} parserOptions 解析器参数
 * @param {function(string)} callback 编译完成回调函数
 */
function compileLessAsync( code, parserOptions, callback ) {
    // less没有提供sync api
    var less = require( 'less' );
    var parser = new( less.Parser )( parserOptions );

    parser.parse(
        code,
        function ( error, tree ) {
            if ( error ) {
                callback( error );
            }
            else {
                try {
                    callback( 
                        null, 
                        tree.toCSS( {
                            compress: !!parserOptions.compress
                        } ) 
                    );
                }
                catch (ex) {
                    callback( { message: 'toCSS fail' } )
                }
            }
        }
    );
};
Ejemplo n.º 7
0
    var compileLess = function (srcFile, options, callback) {
        options = _.extend({
            filename: srcFile
        }, options);
        options.paths = options.paths || [path.dirname(srcFile)];

        var css;
        var srcCode = grunt.file.read(srcFile);

        var parser = new less.Parser(_.pick(options, lessOptions.parse));

        parser.parse(srcCode, function (parse_err, tree) {
            if (parse_err) {
                lessError(parse_err);
                callback(true, '');
            }

            try {
                css = tree.toCSS(_.pick(options, lessOptions.render));
                callback(null, css);
            } catch (e) {
                lessError(e);
                callback(true, css);
            }
        });
    };
Ejemplo n.º 8
0
 krunch.prototype.less = function(job, success, failure){
     var fileOut = job.output,
         fileIn = this.concatFiles(job.files),
         parser = new(less.Parser)({
             paths: job.import_paths,
             filename: path.basename(fileOut)
         });
     try{
         parser.parse(fileIn, function(e, tree){
             if(e) throw 'Error trying to parse less';
             try{
                 fs.writeFileSync(fileOut, tree.toCSS({ compress: job.minify }), 'utf8');
                 if(success) success(this);
                 winston.info('LESS Compiler Output: '+fileOut);
             }
             catch(e){
                 throw 'Couldn\'t save '+fileOut;
             }
         });
     }
     catch(e){
         if(failure) failure(e, this);
         winston.error(util.inspect(e));
     }
     return this;
 };
Ejemplo n.º 9
0
	fs.readFile( styles('style.less'), {encoding: 'utf8'}, function( err, body ){
		if( err ) throw err;
		body = String(body);
		var parser = new(less.Parser)({
			paths: [ styles('') ],
			filename: styles('style.less')
		});

		parser.parse( body, function( err, tree ){
			if( err ){
				msg('LESS Error: ', err );
				return;
			}
			var css;
			try {
				css = tree.toCSS({ compress: options.compress });
			} catch( e ){
				msg('Less Error: ', e );
				return;
			}
			fs.writeFile( options.css + 'style.css', css, function( err ){
				if( err ) throw err;
				msg('wrote style.css');
			});
		});


		/*less.render( body, function( err, css ){
			if( err ) throw err;
			fs.writeFile( options.css + 'style.css', css, function( err ){
				if( err ) throw err;
				msg('wrote style.css');
			});
		});*/
	});
Ejemplo n.º 10
0
exports.server = function (body, file, next) {
    var basedir = path.dirname(file),
        parser = new(less.Parser)({paths : [basedir], silent : true});

    var reportError = function (e) {
        var fileName = e.filename ? e.filename.slice(basedir.length+1) : "Onbekend", //chop of the srcDir (to shorten the filename)
            jsonErr = JSON.stringify("There was a error in your Less: " + e.message.replace(/[\r\n]/g, "") + " in file " + fileName);

        var errorCSS = [
            'body:before {',
            '   content:' + jsonErr + ';',
            '   display:block;',
            '   padding:10px;',
            '   margin:0 auto;',
            '   color:#fff;',
            '   background-color:#c00;',
            '   font:20px sans-serif;',
            '}'
        ];
        next( null, errorCSS.join("\n") );
    }

    parser.parse(body, function (e, root) {
        if(e)
            return reportError(e);

        try {
            next(null, root.toCSS()); //root.toCSS throws an error!
        }
        catch(e) {
            reportError(e);
        }
    });
}
Ejemplo n.º 11
0
                fs.readFile( filepath, 'utf8', function( err, data ) {
                    if( err ) 
                        return next( err );

                    /* parse less & convert to css */
                    var parser = new less.Parser({
                        filename: filepath,
                        paths: k.hierarchy.paths( req.kern.website, 'css' )
                    });

                    console.log( filepath );

                    parser.parse( data, function( err, tree ) {
                        if( err )
                            return next( err );

                        try {
                            var css = tree.toCSS();
                            res.set( 'Content-Type', 'text/css' );
                            res.send( css );
                            lessCache.set( filepath, css );
                        }
                        catch( e ) {
                            console.log( "LESS-Error".bold.red, e.toString() );
                            next( e );
                        }
                    });
                });
Ejemplo n.º 12
0
lessify = function (input, output, cb) {
  var LESS_DIR = path.join(input, 'less')
    , CSS_DIR = path.join(LESS_DIR, 'css')
    , OUTPUT_FILE = path.join(output, 'css', 'styles.css')
    , INDEX_FILE = path.join(LESS_DIR, 'index.less')
    , parser = new (less.Parser)({
        paths: [LESS_DIR],
        filename: 'index.less'
      })
    , inBuff
    , outBuff;

    inBuff = fs.readFileSync(INDEX_FILE).toString();

    parser.parse(inBuff
      , function (e, tree) {
        if(e) {
          return cb(e);
        }

        outBuff = tree.toCSS({ compress: true });

        utils.file.mkdirP(path.dirname(OUTPUT_FILE));

        // Delete the LESS dir, no need for it anymore!
        utils.file.rmRf( LESS_DIR , {silent:true});

        fs.writeFileSync(OUTPUT_FILE, outBuff);

        cb();
    });
};
Ejemplo n.º 13
0
    return function (e, data) {
        if (e) {
            console.log("lessc: " + e.message);
        }

        var parser = new(less.Parser)({
            paths: [path.dirname(input)],
            optimization: 0,
            filename: input
        });

        parser.parse(data, function (err, tree) {
            if (err) {
                less.writeError(err, options);
            } else {
                try {
                    var css = tree.toCSS({ compress: false });
                    if (output) {
                        var fd = fs.openSync(output, "w");
                        fs.writeSync(fd, css, 0, "utf8");
                    } else {
                        util.print(css);
                    }
                } catch (e) {
                    less.writeError(e, options);
                }
            }
        });
    };
Ejemplo n.º 14
0
		fs.readFile(src, function(err, data) {
			if (err) { return next(); }

			var parser = new less.Parser({
				paths: [
					path.join(
						root,
						path.dirname(pathname)
					)
				],
				filename: path.basename(src)
			});

			parser.parse(new String(data), function(err, tree) {
				if (err) {
					if (options.debug) {
						less.writeError(err);
					}

					return res.send(500);
				}

				res.set('Content-Type', 'text/css');
				res.send(tree.toCSS({ compress: options.compress }));
			});
		});
Ejemplo n.º 15
0
			my.compile = function(file, callback){
				var lessfile, cssfile, parser;

				this.length += 1;

				lessfile = this.getPath(this.options.lessPath, file, "less");
				cssfile = this.getPath(this.options.cssPath, file, "css");
				parser = new less.Parser({
					paths : [
						path.dirname(less),
						this.options.lessPath
					] 
				});
				parser.parse(grunt.file.read(lessfile), function(error, tree){
					try {
						if(error){
							my.log(error, true);
							my.errors += 1;
						} else {
							grunt.file.write(cssfile, tree.toCSS({
								compress : my.options.compress
							}));
							my.log(cssfile + " <= " + lessfile);
						}
					} catch(e){
						my.lessError(e, lessfile);
						my.errors += 1;
					}
					callback();
				});
			};
Ejemplo n.º 16
0
Archivo: assets.js Proyecto: adba/sails
 }, function(error) {
     if(error) self.emit('error', error);
     var parser = new less.Parser()
     parser.parse(self.lessContents, function(error, tree) {
         if (error) return next(error)
         var lessAsset = new rack.Asset({
             url: '/assets/styles/style.less.css',
             mimetype: 'text/css',
             contents: tree.toCSS()
         });
         lessAsset.isDev = true;
         self.assets.push(lessAsset);
         lessAsset.on('complete', function() { 
             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');
         })
     })
 });
Ejemplo n.º 17
0
function finish(loader) {
	var parser, code, cssFile, sheet, report, i;
	
	report = function(cssFile) {
		return function(err, tree) {
			if (err) {
				console.error(err);
			} else {
				var css =
					"/* WARNING: This is a generated file for backward-compatibility.  Most      */\n" +
					"/* usrs should instead modify LESS files.  If you choose to edit this CSS   */\n" +
					"/* directly rather than LESS files, you should make sure less.xx.yy.min.js  */\n" +
					"/* is commented out in your debug.html, and run deploy.sh/bat using the     */\n" +
					"/* '-c' flag to disable LESS compilation.  This will force the loader and   */\n" +
					"/* minifier to fall back to using CSS files in place of the same-name       */\n" +
					"/* LESS file.                                                               */\n" +
					"\n" + tree.toCSS();
				fs.writeFileSync(cssFile, css, "utf8");
			}
		};
	};

	for (i=0; (sheet=loader.sheets[i]); i++) {
		if (sheet.slice(-5) == ".less") {
			w(sheet);
			code = fs.readFileSync(sheet, "utf8");
			parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
			cssFile = sheet.slice(0,sheet.length-5) + ".css";
			parser.parse(code, report(cssFile));
		}
	}
}
Ejemplo n.º 18
0
target.dashboard = function() {
  cd(__dirname);

  var lessSource = cat('lib/resources/dashboard/stylesheets/style.less');

  if (lessSource) {
    var parser = new(less.Parser)({
      paths: ['lib/resources/dashboard/stylesheets'], // Specify search paths for @import directives
      filename: 'style.less' // Specify a filename, for better error messages
    });

    parser.parse(lessSource, function (e, tree) {
      if (e) return console.error(e.message);  
      tree.toCSS().to('lib/resources/dashboard/stylesheets/style.css');
    });

  }


  // var result = exec('lessc lib/resources/dashboard/stylesheets/style.less', {silent: true});
  // if (result.code) {
  //   console.error(result.output);
  // } else {
  //   result.output.to('lib/resources/dashboard/stylesheets/style.css')
  // }
}
Ejemplo n.º 19
0
        registerBundle: function(name, customGruntConfig, bundleOptions, sections) {
          var gruntConfig = this.gruntConfig;

          gruntConfig.less = gruntConfig.less || {};
          gruntConfig.less[name] = gruntConfig.less[name] || {};
          gruntConfig.less[name].files = gruntConfig.less[name].files || {};
          gruntConfig.less[name].files[bundleOptions.path + name + '.min.css'] = 'less/' + name + '.less';
          gruntConfig.less[name].options = {
            sourceMap: true,
            sourceMapFilename: bundleOptions.path + name + '.min.css.map'
          };

          gruntConfig.watch = gruntConfig.watch || {};
          gruntConfig.watch['less-' + name] = gruntConfig.watch['less-' + name] || {
            files: [ 'less/' + name + '.less' ],
            tasks: [ 'less:' + name ]
          };

          var parser = new(less.Parser)({ syncImport: true, paths: ['less'], filename: name + '.less' }),
              bundleFile = fs.readFileSync('less/' + name + '.less', { encoding: 'utf-8' });

          parser.parse(bundleFile, function() {
            for(var file in parser.imports.files) {
              gruntConfig.watch['less-' + name].files.push(file);
            }
          });
        }
Ejemplo n.º 20
0
        run: function(e, done) {

            var data = e.all.map(function(f) {

                var src = f.data.toString();
                if (e.config.options.pathPrefix) {
                    src = src.replace(/url\(("|'|)/g, 'url($1' + e.config.options.pathPrefix);

                } else {
                    var base = path.dirname(f.source);
                    src = src.replace(/url\(("|'|)/g, function(m, l) {
                        return 'url(' + l + base + '/';
                    });
                }

                return src;

            });

            var parser = new less.Parser({
                paths: [e.options.src]
            });

            // TODO support source maps
            parser.parse(data.join('\n\n'), function(err, tree) {
                done(err, err || tree.toCSS({
                    sourceMap: e.options.sourceMaps !== false ? true : false,
                    compress: e.options.compress
                }));
            });

        }
					fs.readFile( lessFilePath, 'utf-8', function( err, data ) {
						if( err ) {
							console.log( "Express LESS Middleware: File could not be read." );
							return next(); // if it's cant read the file data, go on and let the user know
						}

						// figuring out length of array so i can slice off the last arugement when putting it back together
						var filePathArrayLength = lessFilePath.split( '/' ).length;

						// creating a less parser with the path that the file was found (for @imports)
						var parser = new( less.Parser )({
							paths: [ lessFilePath.split( '/' ).slice( 0, filePathArrayLength - 1 ).join( '/' ) + '/' ]
						});

						// parsing the file data we've loaded into css
						parser.parse( data, function( err, tree ) {
							if( err ) {
								console.log( "Express LESS Middleware: LESS could not be compiled. ", lessFilePath );
								return next();
							}

							// sending back what we compiled
							res.setHeader( 'Content-Type', 'text/css; charset=UTF-8' );
							res.send( tree.toCSS() );
						});
					});
Ejemplo n.º 22
0
 return function(req, res, next) {
   if (pathnames.indexOf(req.url) != -1) {
     var lessPath = path.join(dirname, req.url.slice(1, -4) + '.less');
     var lessCode = fs.readFileSync(lessPath, 'utf-8');
     var parser = new less.Parser({
       paths: [path.dirname(lessPath)],
       filename: lessPath
     });
     return parser.parse(lessCode, function(err, tree) {
       if (err) {
         console.log(err);
         return res.send(500);
       }
       try {
         var css = tree.toCSS();
       } catch (e) {
         console.log(e);
         return res.send(500);
       }
       res.contentType('text/css');
       res.send(css);
     });
   }
   next();
 }
Ejemplo n.º 23
0
LESSCompiler.prototype.compile = function(params, callback) {
  var data = params.data;
  var path = params.path;

  var parser = new less.Parser({
    paths: [this.rootPath, sysPath.dirname(path)],
    filename: path,
    dumpLineNumbers: !this.optimize && this.config.dumpLineNumbers
  });

  parser.parse(data, function(error, tree) {
    if (error != null) return callback(error.message);
    var result, err;
    try {
      result = tree.toCSS();
    } catch (ex) {
      err = '' + ex.type + 'Error:' + ex.message;
      if (ex.filename) {
        err += ' in "' + ex.filename + ':' + ex.line + ':' + ex.column + '"';
      }
    }

    return callback(err, {data: result});
  });
};
Ejemplo n.º 24
0
			db.getObjectFields('config', ['theme:type', 'theme:id'], function(err, themeData) {
				var themeId = (themeData['theme:id'] || 'nodebb-theme-vanilla'),
					baseThemePath = path.join(nconf.get('themes_path'), (themeData['theme:type'] && themeData['theme:type'] === 'local' ? themeId : 'nodebb-theme-vanilla')),
					paths = [baseThemePath, path.join(__dirname, '../../node_modules')],
					source = '@import "./theme";',
					x, numLESS;

				// Add the imports for each LESS file
				for(x=0,numLESS=plugins.lessFiles.length;x<numLESS;x++) {
					source += '\n@import "./' + plugins.lessFiles[x] + '";';
				}

				// ... and for each CSS file
				for(x=0,numCSS=plugins.cssFiles.length;x<numCSS;x++) {
					source += '\n@import (inline) "./' + plugins.cssFiles[x] + '";';
				}

				var	parser = new (less.Parser)({
						paths: paths
					});

				parser.parse(source, function(err, tree) {
					if (err) {
						res.send(500, err.message);
						return;
					}

					meta.css.cache = tree.toCSS({
						compress: true
					});
					res.type('text/css').send(200, meta.css.cache);
				});
			});
Ejemplo n.º 25
0
 fs.readFile(file, 'utf8', function(err, data){
   if(err){
     logger.error(err);
     return ;
   }
   var env = {
     paths : [path.dirname(file)]
   };
   
   var parser = new less.Parser(env);
   try{
     parser.parse(data, function(err, tree){
       if(err){
         logger.error(err);
         return ;
       }
       data = tree.toCSS({compress : true}).trim();
       if(data.length !== 0){
         fs.writeFile(cssFile, data.replace(/\n/g, ''), 'utf8', function(err){
           if(err){
             logger.error(err);
           }else{
             logger.info('complie less to file:' + cssFile + ' successful');
           }
         });
       }
     });
   }catch(err){
     logger.error(err);
   }
 });
Ejemplo n.º 26
0
	function compileLess(srcCode, options, callback) {
		var parserOptions = _.pick(options, lessOptions.parse);
		parserOptions.javascriptEnabled = false;

		if (!parserOptions.filename) {
			parserOptions.filename = 'style.less';
		}

		less.Parser.fileLoader = fileLoader(options);
		var parser = new less.Parser(parserOptions);
		var err;

		parser.parse(srcCode, function(parse_err, tree) {
			if (parse_err) {
				err = app.createError(app.ERROR_LESS_PARSE, parse_err);
				callback(err, srcCode);
				return;
			}

			try {
				var css = tree.toCSS(_.pick(options, lessOptions.render));
				callback(null, css);
			}
			catch (e) {
				err = app.createError(app.ERROR_LESS_RENDER, lessError(e));
				callback(err, srcCode);
			}
		});
	}
Ejemplo n.º 27
0
	var readAndParse = function(sheets) {
		var sheet = sheets.shift();
		if (sheet) {
			w(sheet);
			var isLess = (sheet.slice(-4) == "less");
			if (isLess && (opt.less !== undefined)) {
				sheet = sheet.slice(0, sheet.length-4) + "css";
				isLess = false;
				w(" (Substituting CSS: " + sheet + ")");
			}
			var code = fs.readFileSync(sheet, "utf8");
			if (isLess) {
				var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
				parser.parse(code, function (err, tree) {
					if (err) {
						console.error(err);
					} else {
						addToBlob(sheet, tree.toCSS());
					}
					readAndParse(sheets);
				});
			} else {
				addToBlob(sheet, code);
				readAndParse(sheets);
			}
		} else {
			doneCB(blob);
		}
	}
Ejemplo n.º 28
0
  builder.hook('before styles', function (builder, callback) {
    if(!builder.root) {
      if(!builder.config.styles) return callback();
      builder.config.styles.forEach(function(file){
        isLess(file) && builder.removeFile('styles', file);
      });
      return callback();
    }
    builder.config.styles.slice().forEach(function(file){
      if(isLess(file) && !~lessImport.indexOf(builder.path(file))){
        lessImport.push(builder.path(file));
      }
			isLess(file) && builder.removeFile('styles', file);
    });
    var importsLess = "";
    lessImport.forEach(function(file){
      importsLess+='@import "'+file +'";\n';
    });
    var parser = new less.Parser(options.env || {});
		var cssConfig = options.cssConfig || {};
    parser.parse(importsLess, function (error, tree) {
      if (error) {
				return callback(error);
			}
			var css = tree.toCSS(cssConfig);
      
			builder.addFile('styles', "compiledLess", css);
		  callback()
    });
	});
Ejemplo n.º 29
0
 _readFromLess: function(file){
   var _this = this;
   console.log('read file source form less');
   try {
     var less = require('less');
     var parser = new(less.Parser)({
       paths: [path.dirname(file)], 
       filename: path.basename(file)
     });
     var css = fs.readFileSync(file);
     parser.parse(css.toString(), function lessc(err, tree){
       if (err){
         console.log(err);
         process.exit(0);
       } else {
         var text = tree.toCSS();
         _this.text = text || true;
         _this.run();
       }
     });
   } catch(e){
     console.log('please install lessc first, run npn install less -g');
     process.exit(0);
     throw e;
   }
 },
Ejemplo n.º 30
0
function compileLess(file, cb){
  var lessCode = FSManager.readFile(file);
  var parser = new(less.Parser)({
    paths: [path.dirname(config.dir + '/' + file)],
    filename: file
  });


  var cssFileName = '/tmp/' + file.replace(/\//g,'__') + '.css';
  console.log("Comipling LESS: " + file + " - " + cssFileName)
  
  parser.parse(lessCode, function (e, tree) {
    if(e){
      console.log(e);
      console.log('Error compiling less file: ' + file);
      console.log('Cannot continue with the build. Exiting...');
      process.exit(1);
    }
    FSManager.writeFile(config.dir + cssFileName, tree.toCSS({
      compress: true
    }));
    cb(cssFileName);
  });

}