The bundles are handy for the global files that need to be included everywhere, but nearly every page has it’s own specific CSS or JS files that needs to be linked to, ideally minified as well, and possibly combined when there are multiples.
In razor, here’s the syntax we use to link to these files:
@Html.Style("~/Styles/someFile.css") @Html.Script("~/Scripts/foo.js", "~/Scripts/bar.js")
Pretty easy right? Just link right the the file, or multiple files and they will be included on the page, but in production they will be minified and combined when multiples exist. How is this done you might ask? Well, take a look at this class below that gives us some extensions in the
MakeBundleName function will make the filename for the bundle (duh). Let’s say you provide it with the two script paths from the usage example above. The final output url for the bundle would be
~/Scripts/bundles/Scripts.foo+Scripts.bar – Basically it just replaces slashes with dots and concatenates multiple files with a plus. This allows for a unique name, but it also won’t change between page loads since it’s based on the input file names.
This all came about from a StackOverflow question I helped answer. There are a few caveats to this method that could be improved upon, the biggest of which is that this will automatically decide the bundle path for you. This means that relative paths inside of your CSS/JS files will not work when the bundle URL is used! For our use case, this is fine, but for what you do, it might not. It would be fairly easy to extend this to have a different syntax like this if needed:
@Html.Script("~/bundles/my/custom/path", "~/Scripts/foo.js", "~/Scripts/bar.js")
Questions? Comments? Improvements? Let me know!