Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundle Script and CSS from Resources in Assemblies for MVC

I have been using Bundles in MVC to pack all script and CSS together which is great but.... Is there any way to include script or css from resources in a shared project library in a Bundle, or does anyone know of something similar to bundles that can do this?

like image 733
Paul Johnson Avatar asked Nov 14 '22 04:11

Paul Johnson


1 Answers

I would probably start out writing a custom bundle transform class to read the resources you need and return their content and content type:

public class ResourceTransform : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        string result;

        using (Stream stream = Assembly.GetExecutingAssembly()
            .GetManifestResourceStream("YourAssemblyNamespace.YourResourceFolder.YourFile.css"))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                result = reader.ReadToEnd();
            }
        }

        response.ContentType = "text/css";
        response.Content = result;
    }
}

For production use you probably want to make the ResourceTransform class a little bit less hardcoded and send the resources you want as params or properties, but you get the idea.

That way you can add this bundle to your collection:

Bundle resources = new Bundle("~/css/resources");
    resources.Transforms.Add(new ResourceTransform());
    resources.Transforms.Add(new CssMinify());

bundles.Add(resources);
like image 116
Martin Buberl Avatar answered Jun 02 '23 09:06

Martin Buberl