MVC4 Less Bundle @import Directory

前端 未结 10 833
南方客
南方客 2020-12-12 17:02

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/
             


        
10条回答
  •  悲&欢浪女
    2020-12-12 17:46

    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));
        }
    }
    

提交回复
热议问题