Bundle Script and CSS from resources in assemblies for MVC

I use Bundles in MVC to pack all script and CSS together, which is fine, but ... Is there a way to include script or css from resources in a shared project library in the Bundle, or does anyone know something similar to packages that can do it?

+5
source share
1 answer

I would probably start writing my own package conversion class to read the resources you need and return their contents 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 class a ResourceTransformlittle less hard-coded and send the resources you need as parameters or properties, but you get this idea.

So you can add this kit to your collection:

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

bundles.Add(resources);
+1
source

All Articles