Blisco
Blisco

Reputation: 620

Stop Bundle Transformer converting relative paths in LESS

I am using Bundle Transformer for LESS compilation in an MVC5 project. My LESS bundle comprises a single main.less file which imports other files located in subfolders. Some of files contain references to image files like so - this is in the file /css/structure/header.less:

.site__logo {
    background: url('../img/logo.png') no-repeat;
    // ...
}

In the compiled bundle (/css/lessBundle) this becomes:

background: url('/css/img/logo.png') no-repeat;

I want the relative path in the .less file to be preserved when it is bundled so that it correctly points to /img/logo.png, not /css/img/logo.png. I think Bundle Transformer is responsible for converting the relative paths -- the documentation has this paragraph, but doesn't go into further detail:

You also need to understand that when you plug instances of CssTransformer and JsTransformer classes, then you plug in a set of transformations (choice between debug and pre-minified versions of files, translation code from the intermediate languages, runtime code minification, transformation of relative paths to absolute (only for CSS-code) and code combining). A set of transformations depends on what the modules of Bundle Transformer you have installed and settings you have specified in the Web.config file.

Here is my BundleConfig:

public class BundleConfig
{
    public const string LessBundlePath = "~/css/lessBundle";

    public static void RegisterBundles(BundleCollection bundles)
    {
        var nullBuilder = new NullBuilder();
        var cssTransformer = new CssTransformer();
        var nullOrderer = new NullOrderer();

        // Skip JS-related stuff

        var lessBundle = new Bundle(LessBundlePath)
            .Include("~/css/main.less");
        lessBundle.Builder = nullBuilder;
        lessBundle.Transforms.Add(cssTransformer);
        lessBundle.Orderer = nullOrderer;
        bundles.Add(lessBundle);

        BundleTable.EnableOptimizations = true;
    }
}

/css/main.less is mostly just a bunch of imports:

@import "bootstrap/bootstrap";
@import "structure/header";
// etc.

html, body {
height: 100%;
}

I have tried playing with this setting in web.config, but to no effect:

<css defaultMinifier="NullMinifier" disableNativeCssRelativePathTransformation="true">

If possible I would rather not alter the filepaths in the .less files, as they are provided by a third party and everything works fine on their integration server (which is not using .NET). Is there anything else I can do?

Upvotes: 5

Views: 1622

Answers (2)

Andrey Taritsyn
Andrey Taritsyn

Reputation: 1286

In the BundleTransformer.Less and BundleTransformer.SassAndScss modules cannot be disable transformation of relative paths to absolute, because it can break the references to images when using @import directives.

To get /img/logo.png instead of /css/img/logo.png you just need to correctly specify a relative path in the source code (../../img/logo.png instead of ../img/logo.png).

Upvotes: 2

arserbin3
arserbin3

Reputation: 6148

I solved this a while back, before MVC had any sort of support for LESS files. Just tested to verify, and this class will correctly apply the current folder of an @imported .less when transforming it to CSS.

BundleHelper.cs :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Optimization;
using dotless.Core;
using dotless.Core.Abstractions;
using dotless.Core.Importers;
using dotless.Core.Input;
using dotless.Core.Loggers;
using dotless.Core.Parser;

public static class BundleHelper
{
    internal class LessBundle : StyleBundle
    {
        public LessBundle(string virtualPath)
            : base(virtualPath)
        {
            // inject LessTransform to the beginning of the Transforms
            Transforms.Insert(0, new LessTransform());
        }

        public LessBundle(string virtualPath, string cdnPath)
            : base(virtualPath, cdnPath)
        {
            // inject LessTransform to the beginning of the Transforms
            Transforms.Insert(0, new LessTransform());
        }
    }

    // TODO: speed improvement - consider not parsing any CSS files that are not LESS
    // TODO: verify that this still works for nested @imports
    internal class LessTransform : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse bundle)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (bundle == null)
                throw new ArgumentNullException("bundle");

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            // initialize variables
            var lessParser = new Parser();
            ILessEngine lessEngine = CreateLessEngine(lessParser);
            var content = new StringBuilder(bundle.Content.Length);
            var bundleFiles = new List<BundleFile>();

            foreach (var bundleFile in bundle.Files)
            {
                bundleFiles.Add(bundleFile);

                // set the current file path for all imports to use as the working directory
                SetCurrentFilePath(lessParser, bundleFile.IncludedVirtualPath);

                using (var reader = new StreamReader(bundleFile.VirtualFile.Open()))
                {
                    // read in the LESS file
                    string source = reader.ReadToEnd();

                    // parse the LESS to CSS
                    content.Append(lessEngine.TransformToCss(source, bundleFile.IncludedVirtualPath));
                    content.AppendLine();

                    // add all import files to the list of bundleFiles
                    ////bundleFiles.AddRange(GetFileDependencies(lessParser));
                }
            }

            // include imports in bundle files to register cache dependencies
            if (BundleTable.EnableOptimizations)
                bundle.Files = bundleFiles.Distinct();

            bundle.ContentType = "text/css";
            bundle.Content = content.ToString();
        }

        /// <summary>
        /// Creates an instance of LESS engine.
        /// </summary>
        /// <param name="lessParser">The LESS parser.</param>
        private ILessEngine CreateLessEngine(Parser lessParser)
        {
            var logger = new AspNetTraceLogger(LogLevel.Debug, new Http());
            return new LessEngine(lessParser, logger, true, false);
        }

        // TODO: this is not currently working and may be unnecessary.
        /// <summary>
        /// Gets the file dependencies (@imports) of the LESS file being parsed.
        /// </summary>
        /// <param name="lessParser">The LESS parser.</param>
        /// <returns>An array of file references to the dependent file references.</returns>
        private static IEnumerable<BundleFile> GetFileDependencies(Parser lessParser)
        {
            foreach (var importPath in lessParser.Importer.Imports)
            {
                var fileName = VirtualPathUtility.Combine(lessParser.FileName, importPath);
                var file = BundleTable.VirtualPathProvider.GetFile("~/Content/test2.less");

                yield return new BundleFile(fileName, file);
            }

            lessParser.Importer.Imports.Clear();
        }

        /// <summary>
        /// Informs the LESS parser about the path to the currently processed file.
        /// This is done by using a custom <see cref="IPathResolver"/> implementation.
        /// </summary>
        /// <param name="lessParser">The LESS parser.</param>
        /// <param name="currentFilePath">The path to the currently processed file.</param>
        private static void SetCurrentFilePath(Parser lessParser, string currentFilePath)
        {
            var importer = lessParser.Importer as Importer;

            if (importer == null)
                throw new InvalidOperationException("Unexpected dotless importer type.");

            var fileReader = importer.FileReader as FileReader;

            if (fileReader != null && fileReader.PathResolver is ImportedFilePathResolver)
                return;

            fileReader = new FileReader(new ImportedFilePathResolver(currentFilePath));
            importer.FileReader = fileReader;
        }
    }

    public class ImportedFilePathResolver : IPathResolver
    {
        private string _currentFileDirectory;
        private string _currentFilePath;

        public ImportedFilePathResolver(string currentFilePath)
        {
            if (String.IsNullOrEmpty(currentFilePath))
                throw new ArgumentNullException("currentFilePath");

            CurrentFilePath = currentFilePath;
        }

        /// <summary>
        /// Gets or sets the path to the currently processed file.
        /// </summary>
        public string CurrentFilePath
        {
            get
            {
                return _currentFilePath;
            }

            set
            {
                var path = GetFullPath(value);
                _currentFilePath = path;
                _currentFileDirectory = Path.GetDirectoryName(path);
            }
        }

        /// <summary>
        /// Returns the absolute path for the specified imported file path.
        /// </summary>
        /// <param name="filePath">The imported file path.</param>
        public string GetFullPath(string filePath)
        {
            if (filePath.StartsWith("~"))
                filePath = VirtualPathUtility.ToAbsolute(filePath);

            if (filePath.StartsWith("/"))
                filePath = HostingEnvironment.MapPath(filePath);
            else if (!Path.IsPathRooted(filePath))
                filePath = Path.GetFullPath(Path.Combine(_currentFileDirectory, filePath));

            return filePath;
        }
    }
}

Example Usage:

  • App_Start / BundleConfig.cs :

    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new BundleHelper.LessBundle("~/Content/css").Include(
                "~/Content/normalStuff.css",
                "~/Content/template.less",
                "~/Content/site.less"));
        }
    }
    
  • Content / template.less :

    @import "themes/blue/test";
    
    body {
        background: url('../img/logo.png') no-repeat;
    }
    
    footer {
        background: url('img/logo1.png') no-repeat;
    }
    
  • Content / themes / blue / test.less :

    .myTheme {
        background: url('../img/logo2.png') no-repeat;
    }
    
    .myTheme2 {
        background: url('img/logo3.png') no-repeat;
    }
    

Using this bundle will output the following CSS, which should be just what you're looking for:

  • location: example.com/path/Content/test.less

    .myTheme {
      background: url('themes/img/logo2.png') no-repeat;
    }
    .myTheme2 {
      background: url('themes/blue/img/logo3.png') no-repeat;
    }
    body {
      background: url('../img/logo.png') no-repeat;
    }
    footer {
      background: url('img/logo1.png') no-repeat;
    }
    

NOTE: Based on old comments of mine, I'm not sure how well it will handle nested @imports (imports inside the test.less to yet a different folder)

Let me know if this doesn't work for you.

Upvotes: 0

Related Questions