I\'m trying to use MVC4 bundling to group some of my less files, but it looks like the import path I\'m using is off. My directory structure is:
static/
Here's the simplest version of the code to handle this I could come up with:
public class LessTransform : IBundleTransform
{
public void Process(BundleContext context, BundleResponse bundle)
{
var pathResolver = new ImportedFilePathResolver(context.HttpContext.Server);
var lessParser = new Parser();
var lessEngine = new LessEngine(lessParser);
(lessParser.Importer as Importer).FileReader = new FileReader(pathResolver);
var content = new StringBuilder(bundle.Content.Length);
foreach (var bundleFile in bundle.Files)
{
pathResolver.SetCurrentDirectory(bundleFile.IncludedVirtualPath);
content.Append(lessEngine.TransformToCss((new StreamReader(bundleFile.VirtualFile.Open())).ReadToEnd(), bundleFile.IncludedVirtualPath));
content.AppendLine();
}
bundle.ContentType = "text/css";
bundle.Content = content.ToString();
}
}
public class ImportedFilePathResolver : IPathResolver
{
private HttpServerUtilityBase server { get; set; }
private string currentDirectory { get; set; }
public ImportedFilePathResolver(HttpServerUtilityBase server)
{
this.server = server;
}
public void SetCurrentDirectory(string fileLocation)
{
currentDirectory = Path.GetDirectoryName(fileLocation);
}
public string GetFullPath(string filePath)
{
var baseDirectory = server.MapPath(currentDirectory);
return Path.GetFullPath(Path.Combine(baseDirectory, filePath));
}
}