3

我正在使用 mvc4 并探索 css 和 javascript 的捆绑是如何工作的。我有一个需要帮助的问题。

对于我呈现的每一页(视图),我只想拥有一个 js 和 css 文件。这是该视图所需的多个文件的结果。从我所见,我可以创建文件包,但我没有看到为每个视图创建包的方法。

如果可以实现我概述的内容,有人可以帮助我吗?

4

2 回答 2

1

What you need to do is go to Static>App_Start>BundleConfig.cs :

Bundle Config path

and then create a bundle for each view you have:

public class BundleConfig
{
    // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/GlobalScripts")
                            .Include("~/Static/Scripts/jquery-1.10.2.js"
                                    , "~/Static/Scripts/json2.js"
                                    , "~/Static/Scripts/jquery-ui-1.10.4.js"
                                    //, "~/Static/Scripts/jquery.layout-1.3.0.js"
                                    //, "~/Static/Scripts/jquery.layout.state.js"
                                    , "~/Static/Scripts/helper.mainlayout.js"));
    }
}

just keep adding your script path in .Include() for every javascript in the view and keep doing bundles.add(new ScriptBundle(<bundle path>)) for every view you have.

you will do the similar steps with CSS bundles, but instead of using ScripBundle you will use StyleBundle

To lessen the repetition of codes try creating a list of strings for every javascripts that are dependent to one another and do a union on them:

List<string> jqGridScripts = new List<string>
                             {"~/Static/Scripts/jquery.jqGrid.src.js"
                             , "~/Static/Scripts/i18n/grid.locale-en.js"
                             , "~/Static/Scripts/helper.jqgrid.js"};
List<string> jqStopwatch = new List<string> 
                             { "~/Static/Scripts/jquery.stopwatch.js" };

bundles.Add(new ScriptBundle("~/bundles/viewName")
                             .Include(jqGridScripts
                                     .Union(jqStopwatch).ToArray()));

Just remember that the order in which they appear on the array is the same order in which they will appear on the HTML or be bundled and minified.

Code in View:

@section scripts{
    @Scripts.Render("~/bundles/viewName");
}

Resultant Code in HTML

<script src="/WDCSS/bundles/viewName?v=T3IlBuvfGTiz62pwDuiPogFX1jQoxVC2tmp3K6wffBQ1"></script>

My Opinion

I don't really know if we should do this or not. For me I separate scripts that are used in all pages in a separate bundle so that it would be cached. and then create another bundle for the scripts used in a view. What I am trying to say is that we should achieve a balance between bundling, minification, and caching.

于 2015-02-23T04:49:59.263 回答
1

更具体地回答您的问题。向我们展示您的尝试。您必须手动创建每个捆绑包。如果您希望在特定视图上使用捆绑包,请创建这样的捆绑包并在视图中指定您将在那里使用该捆绑包,就像您在视图中指定您将在那里使用 css 文件一样。

于 2012-12-31T03:52:01.273 回答