MVC Bundling Not Working

2019-02-23 08:04发布

问题:

I am working on a small mvc project, i have declared a bundle in BundleConfig.cs like this

//javascript bundle

bundles.Add(new ScriptBundle("~/bundles/Layout1JS").Include(
                        "~/Content/Public/js/jquery.min.js",
                        "~/Content/Public/js/bootstrap.min.js",
                        "~/Content/Public/js/jquery.isotope.min.js",
                        "~/Content/Public/js/jquery.Photo.js",
                        "~/Content/Public/js/easing.js",
                        "~/Content/Public/js/jquery.lazyload.js",
                        "~/Content/Public/js/jquery.ui.totop.js",
                        "~/Content/Public/js/nav.js",
                        "~/Content/Public/js/sender.js",
                        "~/Content/Public/js/jquery.slider-min.js",
                        "~/Content/Public/js/custom.js"));


//css bundle
bundles.Add(new StyleBundle("~/Content/Public/css").Include(
                        "~/Content/Public/css/main.css"));

In my _Layout.cshml in the head section i have entered:

<head>
    <meta charset="utf-8">
    <title>test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- LOAD CSS FILES -->
    @Styles.Render("~/Content/Public/css", "~/Content/css")

    <!-- LOAD JS FILES -->


    @Scripts.Render("~/bundles/Layout1JS")

</head>

In my application_start i have:

BundleTable.EnableOptimizations = true; 

and web.config

<compilation debug="true" targetFramework="4.0">

This gave me bit of a headache trying to figure why the bundling isnt working specially for the javascript. Some one please advise

回答1:

The bundling is not working because of this line

<compilation debug="true" targetFramework="4.0">

When in debug, the bundles do not compress or minify as you are "debugging" and being able to see the actual JavaScript and CSS is a good thing when you are debugging. When you have debug set to false (or removed from the tag), then your application is running in release mode. Bundling will occur at that point (unless you set BundleTable.EnableOptimizations = false;)

<compilation debug="false" targetFramework="4.0">

or

<compilation targetFramework="4.0">

As pointed out by Mike below, the BundleTable.EnableOptimizations = true; should override the web.config setting. However, it may still be good to get out of debug mode in the case that your project is not overriding that setting.