ASP.NET Bundles in regular html?
Asked Answered
X

1

4

My angular application is backed by ASP.NET webapi, where I'm serving up an index.html and angular handles everything else from there. I'd like to use bundling, but I can't see how I'd do this. Do I have to use razor (or webforms) just to reference bundles? Or is there an option to give the bundle output a fixed name that I can reference in my src/hrefs?

To clarify, I'm not using MVC or Webforms to serve html. You just get redirected to index.html , and the routing is all client-side. My bundle configuration is done using WebActivator.PostApplicationStartMethod.

Xe answered 2/3, 2014 at 5:14 Comment(3)
so you are using plain html (no asp.net-mvc) and get your data from web api?Warnock
@Warnock - Clarified in original postXe
@GeorgeR did you find a suitable solution for this ? I'm in the same circumstances and I do not manage to deal with bundle refresh (i.e when I do changes in a js file and rebuild the project, the bundle is not refreshed)Cecillececily
C
1

First, to only answer the question, you can just use a plain link in your html file

<script src='bundles/mybundle' type='text/javascript' language='text/javascript'></script>  

=> that will include your javascript bundle into the page

The problem you will have with this approach is that if you modify a *.js file contained in the bundle, the modification will not be visible in the bundle. This is all about "bundle cache busting", a nice feature of ASP.NET but only usable from a razor template ... Obviously, you cal also restart the pool (but this is quite slow and hard to automate) :)

To workaround the problem, you can define your own ASP.NET MVC Controller with the following

using System.Linq;
using System.Web.Mvc;
using System.Web.Optimization;

namespace Controllers
{
    public class DebugBundlesController : Controller
    {
        // GET: debugbundles/mybundle
        public ActionResult Mybundle()
        {
            return InlineBundleJavaScript("~/bundles/mybundle");
        }

        private ActionResult InlineBundleJavaScript(string bundlePath)
        {
            //see https://blog.mariusschulz.com/2015/10/25/inlining-css-and-javascript-bundles-with-asp-net-mvc
            var bundleContext = new BundleContext(HttpContext, BundleTable.Bundles, "~/bundles");
            var bundle = BundleTable.Bundles.Single(b => b.Path == bundlePath);
            var js = bundle.GenerateBundleResponse(bundleContext).Content;
            return JavaScript(js);
        }
    }
}

and you use that like :

<script src='debugbundles/mybundle' type='text/javascript' language='text/javascript'></script>

=> now, every time you make a change, the bundle will be regenerated.

Be aware to use this only during development because you remove nearly all benefits of bundles (i.e in particular client and server caching)

Cecillececily answered 29/12, 2015 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.